Checking which object from a table has been chosen

I want to make it so that whenever a random object has been chosen, something happens to it. I am not sure you can detect what has been printed so that isn’t going to work. Is it a table function that detects when a random object has been chosen?

Here is the script:
redPart = game.Workspace.redPart
yellowPart = game.Workspace.YellowPart
bluePart = game.Workspace.bluePart

objects = {redPart, yellowPart, bluePart}

local function randomPartExplode()
print(objects[math.random(1, #objects)])
end

randomPartExplode()

1 Like

You can store the chosen element as a variable.

redPart = game.Workspace.redPart
yellowPart = game.Workspace.YellowPart
bluePart = game.Workspace.bluePart

objects = {redPart, yellowPart, bluePart}

local function randomPartExplode()
	local choice = objects[math.random(1, #objects)]
	print(choice)
	local explosion = Instance.new("Explosion")
	explosion.Position = choice.Position
	explosion.Parent = workspace
end

randomPartExplode()
3 Likes

Thanks for helping me! I will try to add more to this script. So you first set choice as a variable and gave it a value to what ever random object has been chosen. Then whatever random object that has been chosen it explodes. I am just trying to understand it better by doing this. Thanks though for the help.

Yes. When you do something like
objects[n]
You are getting the n’th member of the list named ‘objects’.

Using:
math.random(1, #objects)
gets a random number between 1 and the number of items in ‘objects’, which is 3 in your example.

So doing this:
objects[math.random(1, #objects)]
will pick a random number between 1 and 3, then select the item with that place in objects.

Then for the explosion, I used Instance.new() which is called a constructor function, and I tell it to specifically create an Explosion object. The constructor returns the newly created object, which I assign a variable.
Then I set the explosion’s Position property to the randomly chosen part, and then I make it render in the world by setting it’s Parent property to game.Workspace.

Thank you for explaining. I will practice this more