✓ Accepted answer
You're getting that error because you're trying to use # on a child of game. If you want to get a random part from the children of your script's parent, you can iterate its children, insert each part into a table, and then pick a random one from that table.
Example:
local t = {}
for i,v in pairs(script.Parent:GetChildren()) do
if v:IsA("BasePart") then
table.insert(t, v)
end
end
local RandomPart = t[math.random(1,#t)]
If you want you can make it into a function aswell
local function GetRandomPart(obj)
local t = {}
for i,v in pairs(obj:GetChildren()) do
if v:IsA("BasePart") then
table.insert(t, v)
end
end
return t[math.random(1,#t)]
end
local part = GetRandomPart(workspace)
6 comments
Thanks! and can you give me loop one? that gets random part repeatly
while wait() do part = GetRandomPart(workspace) end <-- something like this? not sure why would you need that though
now I'm getting this error: "attempt to call method 'GetChildren' (a nil value)" ;-;
You need to pass a valid Instance object as the parameter.
Oh i did...I wrongly wrote "part = randompart(script.parent)" so i fixed it with my hands :D Thanks again!
Feel free to accept the answer