I am trying to use a script where a billboard gui pops up on the closest part to the player that the player spawned using a button. I tried using this script:
local plrName = script.Parent.Name local rK = game.Players:GetPlayerFromCharacter(script.Parent).PlayerGui:WaitForChild("RKeyGen") n = nil while true do for i, v in pairs(game.Workspace.Bricks:GetChildren())do if v.Name == plrName then local pPos = v.Position local lPos = script.Parent:FindFirstChild("HumanoidRootPart").Position local sAway = (pPos - lPos).magnitude if sAway ~= nil then v:FindFirstChild("NumVal").Value = tonumber(sAway) print(sAway) if n ~= nil then if v:FindFirstChild("NumVal").Value > n then rK.Enabled = true rK.Adornee = v else n = v:FindFirstChild("NumVal").Value end else n = v:FindFirstChild("NumVal").Value end end end end wait(0.15) end
It works sometimes, but then an error occurs randomly and says: "Workspace.snaks308070.Script:12: attempt to index a nil value"
Any help?
I'm going to assume the error is coming from Line 12 based on the Output? (Tell me if I'm wrong) Assuming that's the case, when the script runs, there may not be a "NumVal" so you may want to change the line from
v:FindFirstChild("NumVal").Value = tonumber(sAway)
to
v:WaitForChild("NumVal").Value = tonumber(sAway)
or you could even separate it as
local num = v:WaitForChild("NumVal") num.Value = tonumber(sAway)
Otherwise, move the
print(sAway)
above Line 12 and see what the output is, if it returns nil, then its not reading the sAway value
If you get any errors, and it says : with a number, it's that script line. A nil value error means that it can't find what you are localizing. Use waitforchild instead of findfirstchild in that case so that instead of trying to find it and finding nothing, it will wait until it comes, if you want a different outcome comment