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

Selecting 1 Part out of Multiple

I am working on a project that involves moving platforms. There are around 500 parts in the Workspace with the name 'Part1'. I am going to make each one move a random distance up or down. I am going to use Math.Random to create a number it has to move, but I can't work out how to make each one move a random distance so they all go up and down different distances at varying intervals. I used

game.Workspace:GetChildren()

to select the parts, but this method selects all of the parts instead. I need to know a way to select a certain number of parts and then generate a random number for each one.

2 answers

✓ Accepted answer

Sound like you need a for loop.

for i, v in pairs(game.Workspace:GetChildren()) do --make sure you have the correct path.
	if v:IsA("BasePart") then --this makes sure you're doing something to a part, rather than, say, an IntValue
		--your code (the math.random() statements)
	end
end

GoldenPhysics's answer was correct, however I realize that the IsA method just finds if the ClassName string is the same. I have found that to error when I try BasePart. I can add additional help:

y = math.random(0,100)
for _, v in pairs(game.Workspace:GetChildren()) do
	if v:IsA("Part") and v.Name == "Part1" then
		v.CFrame = CFrame.new(v.Position.X, y, v.Position.Z)
	end
end

The above will make the parts separately move anywhere from 0 to 100 on the Y axis (up down) while keeping their original X and Z positions (left right forward backward). The way I lined that up will have it run math.random several times so it generates a different number every time. Feel free to change the 0, 100 to any other two numbers. Also, this script will make sure the part is named "Part1". If it's not named that it ignores it.

2 comments

0

No, :IsA("BasePart") is so much better. It looks for wedges and other parts that aren't under the ClassName 'Part'.

0

I was only building with Basic Parts.

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