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

Why is the player nil when I call a GUI?

Asked by 5 years ago

When I try to call a GUI, the output's nil, but when I try to print something it works. Here is the code:

p = script.Parent.Position
range = 500-- the range
frame = game.Players.LocalPlayer.PlayerGui.ScreenGui.Frame

while true do
    wait(.1)
    plrs = game.Players:GetChildren()
    for i,plr in ipairs(plrs) do
        if plr.Character ~= nil then
            tor = plr.Character.UpperTorso
            if (p - tor.Position).magnitude <= range then
                print("yay") 
               frame.Visible = true
            else
                frame.Visible = false 
            end
        end
    end
end

Thanks for the Help!

1 answer

Log in to vote
1
Answered by 5 years ago

Your problem is that the player doesn't load in as quickly as scripts, so when the script runs, the player will still be unloaded, aka nil.

To solve this, make a variable for the player, and then reference it where you need to, like so:

local player = game.Players.LocalPlayer or wait() --Checks for player, then if they are not there, wait.
local frame = player.PlayerGui.ScreenGui.Frame --It's also good practice to use local variables.

If this solved your problem, I'd appreciate my answer accepted or upvoted; hope I helped!

0
why does it give me this: attempt to index local 'player' (a number value)? awesomemode14 68 — 5y
0
nevermind, I found my error, Thanks for the Help! awesomemode14 68 — 5y
Ad

Answer this question