Why doesnt random = nil work? let me show what I mean
local random
local part = script.Parent
local folder = game.workspace:waitforchild("Folder")
part.Touched:Connect(function()
random = folder[math.random(1, folder)]
end)
random.Touched:Connect(function()
random = nil --This part doesnt work idk why?
end)
It might be because you’re using the reserved random keyword.
You named the random part variable as random, and since it’s a reserved word in the Luau coding language, the script thinks you’re referring to a built-in library. You can simply change the name of the variable to anything else, like random_part.
Can you elaborate on the results you’re getting from your code? As already mentioned by @BlueBloxBlast your use of math.random() will cause an exception as you’re passing an instance itself and not the number of its children to the function. Additionally the :waitforchild in game.workspace:waitforchild("Folder") is spelled incorrectly. The function is actually called :WaitForChild().
The random being set only when part is touched
You are connecting it to .Touched right after you connected .Touched to part
But because random is nil, it won’t connect it (It should give an error)
This isn’t how Luau works. You’re connecting random.Touched before you assigned a value to variable. You’re just doing nil.Touched, which will give you an error.
You’re also not using folder correctly
local random
local part = script.Parent
local folder = workspace:WaitForChild("Folder")
part.Touched:Connect(function()
local children = folder:GetChildren() -- get the object's children
random = children[math.random(#children)] -- get a random child
random.Touched:Wait() -- wait for the 'Touched' event to fire
random = nil -- reset the variable to nil
end)