Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Script's not working? supposed to randomly clone a specified object into workspace.

Asked by 9 years ago

Okay, let's get this straight im new to .random. I don't understand how it works so could someone help me out here?

Output: 04:11:08.318 - 2 is not a valid member of Lighting 04:11:08.320 - Script 'Workspace.Script', Line 3 04:11:08.320 - Stack End


workspace.ChildAdded:connect(function(child) if child:findFirstChild("Humanoid") then for i,v in pairs(game.Lighting[math.random(1,#game.Lighting:GetChildren())]) do v.Parent = child end end end)

1 answer

Log in to vote
0
Answered by
iaz3 190
9 years ago

math.random returns a random number between, in your case, 1 and the number of objects in lighting. The error is saying "2" is not something that is IN lighting

I propose the following solution, which should randomly select an object from a table of objects, returned by GetChildren()

In the case of the error you received, this script would instead return the second object found in lighting.

Since you are randomly selecting one object, you don't need a loop.

workspace.ChildAdded:connect(function(child)
    if child:findFirstChild("Humanoid") then
        local v = game.Lighting:GetChildren()[math.random(1,#game.Lighting:GetChildren())]
        v.Parent = child
    end
end)
Ad

Answer this question