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

A script that will randomize a parents children and put into a new parent?

I wan't to make a script that will look inside a Parent or "Model" and find all of the children inside and at random pick "1" or "2" childs and put them into a new Parent or "Model" but i don't know how i can use math.random with the script i wan't since i'm pretty new to (math.random)

S = game.Workspace.Model1:GetChildren() --I think i do somthing like this right? But i want it to automatically get all children.
G = math.random(S)--Somthing with this?
C = G:clone()--and everything below should be right.
C.Parent = game.Workspace.Model2

1 answer

✓ Accepted answer

The function math.random returns an integer value when given two arguments, the start of the range and the end of the range. The integer that math.random returns is an integer that is in the inclusive range denoted by the arguments.

e.g. math.random(1, 4) can yield values 1, 2, 3, and 4.

We can use this to pick a random index for the table returned from the GetChildren method. This essentially means 'pick a random child'.

Knowing this we can write a function that will pick a certain number of children of one model and parent a clone of them to another. Said function is shown below:

local function randomParentChildren(model1, model2, numChildren)
	local children = model1:GetChildren()
	for i = 1, numChildren do
		local index = math.random(1, #children)
		children[index]:Clone().Parent = model2
	end
end

3 comments

0

Ew. Numerical fors.

0

Thanks helped a lot, and also thanks for the math.random explanation!

0

What's so bad about numerical for loops?  They are great if you are looking for an index and nothing more. What would you rather see?

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