Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

✓ Accepted answer

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!!

4 comments

0

You could also just put the object reference directly in the table and remove it in less steps!

0

@Perci1 Heh, you're right. Let me offer that example.

0

What I mean was something like, list = {workspace.Part, workspace.Brick} list[math.random(1, #list)]:Destroy() wouldn't that work?

0

@Perci1, Ah, that would work. Although, that seems like it requires a but more typing than my first way, lol

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

This discussion is preserved as it was. New answers, comments, and votes are closed.