How would I parent something randomly?

So, basically I want to parent a ClickDetector to a random part in a model.
How would i achieve this?

I have not tried anything seeing as I’m at a loss of how to do this.

You can use math.random() in a way like this

Clone the click detector
Parent it to model:GetChildren()[math.random(#model:GetChildren())]
Complete

The 2nd line, :GetChildren() returns a table containing all the instances inside the model, math.random() and the argument inside will create a random number from 1 to how many children are inside the model and return a random number from that.

1 Like

Sorry, it’s slightly unclear; but are you saying that, when you join the game, a Clicker would be imported into a random part?

Basically, But a random part inside a specific model.

What do you mean by “random part”

As in, a model has say, 15 parts in it, and I would like the clicker to be parented to one of those parts chosen at random.

Read my reply at the top 1balistic, that should be explained well.

Basically, just parent the clickDetector to a random child.

In the script below, we get the children of the model. This returns a array of the object stored in that model. math.random(min, max) returns a random integer between min and max (inclusive), so we use that to pick a random child. Then, we set the click detector’s parent to it.

local clickDetector = script:WaitForChild('ClickDetector') --Or another path
local modelWithOnlyParts = workspace:WaitForChild('Model') --Or another path

local children = modelWithOnlyParts:GetChildren()
local chosen = children[math.random(1, #children)]
clickDetector.Parent = chosen

To make this script without modification, parent the script to ServerScriptService and the clickDetector to the script. Your model should be named Model and patented to workspace. Obviously, you can change this if you want, but this is how the current code above works.

4 Likes

Worked perfectly to my needs. Thanks!

1 Like