Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do I simplify this script? Random number script with alot of "elseif"

Asked by 9 years ago

I'd really like to simplify this script since I don't want to keep copy and pasting the same 2 lines tons of times once I have put alot of stuff into my game.

math.randomseed(tick())
t = math.random(6)
--
mk1 = 1
mk2 = 2
mk3 = 3
door = 4
wood = 5
robot = 6

--
if t == mk1 then
script.Parent.mk1:Remove()
elseif t == mk2 then
script.Parent.mk2:Remove()
elseif t == mk3 then
script.Parent.mk3:Remove()
elseif t == door then
script.Parent.door:Remove()
elseif t == wood then
script.Parent.wood:Remove()
elseif t == robot then
script.Parent.robot:Remove()
end

2 answers

Log in to vote
2
Answered by
Shawnyg 4330 Trusted Badge of Merit Snack Break Moderation Voter Community Moderator
9 years ago

To simplify it, make a table! Put all the values, have it select a random number, and grab a value from the table! If you want it to keep happening, make a while loop!

myTable = {"mk1","mk2","mk3","door","wood","robot"}

number = math.random(1,#myTable)
part = myTable[number]
script.Parent[part]:Destroy() -- Remove is deprecated!
table.remove(myTable, number) -- Remove it from the table.

Or, as Perci1 stated, you could get the object directly from the table!

myTable = {"mk1","mk2","mk3","door","wood","robot"}

script.Parent[myTable[math.random(1, #myTable)]]:Destroy()
-- The only thing I can't figure out, is how to remove that value from the table, without doing what I did before!!
0
You could also just put the object reference directly in the table and remove it in less steps! Perci1 4988 — 9y
0
@Perci1 Heh, you're right. Let me offer that example. Shawnyg 4330 — 9y
0
What I mean was something like, list = {workspace.Part, workspace.Brick} list[math.random(1, #list)]:Destroy() wouldn't that work? Perci1 4988 — 9y
0
@Perci1, Ah, that would work. Although, that seems like it requires a but more typing than my first way, lol Shawnyg 4330 — 9y
Ad
Log in to vote
-1
Answered by
davness 376 Moderation Voter
9 years ago

Yes, you can do. You do not need an if statement, but a forloop with in pairs function

math.randomseed(tick())
t = math.random(6) -- draw the number

local tt = {"mk1", "mk2", "mk3", "door", "wood", "robot"} -- get the names

for i,v in pairs(tt) do -- read all the contestants
    if i == t then -- if the "loop number" is equal to the number drawn then
        script.Parent:WaitForChild(v):Destroy() -- destroy the selected name
        print ("t == "..t..": "..v.." was selected to be destroyed!") -- print the number drawn and the destroyed part
        break -- stop the loop
    else print ("No match found") -- print no match found if no match found
    end
end

Answer this question