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

I'm getting "attempt to get length of local 'v' (a userdata value)" error,Why? HELP!

I'm trying making something that picks random part but its not working... Heres Script:

while wait(0.5) do
	if script.Parent:IsA("Model") then
		for i,v in pairs(game:GetChildren()) do
			 local Part = v[math.random(1,#v)]
			Part.Material = "Ice"
			wait(1)
			Part:destroy()
			wait(2)
		end
	end
end

1 answer

✓ 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

--use it like this:
local part = GetRandomPart(workspace)

6 comments

0

Thanks! and can you give me loop one? that gets random part repeatly

0

while wait() do part = GetRandomPart(workspace) end <-- something like this? not sure why would you need that though

0

now I'm getting this error: "attempt to call method 'GetChildren' (a nil value)" ;-;

0

You need to pass a valid Instance object as the parameter.

0

Oh i did...I wrongly wrote "part = randompart(script.parent)" so i fixed it with my hands :D Thanks again!

0

Feel free to accept the answer

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