Player = game.Players.LocalPlayer Character = Player.Character gui = script.Parent.Text:Clone() while true do magnitude = (script.Parent.Position - Character.Torso.Position).magnitude if gui.Parent == nil and magnitude < 20 then gui.Parent = game.Players.LocalPlayer.PlayerGui elseif magnitude >= 20 then gui.Parent = nil end wait(0.5) end
This script should sense when a player is close enough to a certain object to trigger an event. However, it only works when I delete it and paste it again. After a character dies, the gui doesn't show up until I delete and paste it again. Why does it do this?
EDIT: Hierarchy
Part Script (this script) Text (ScreenGui) Stuff inside Text, irrelevant
EDIT2: New script
Player = game.Players.LocalPlayer repeat wait() until Player.Character Character = Player.Character gui = script.Parent.Text:Clone() while true do magnitude = (script.Parent.Position - Character.Torso.Position).magnitude if gui.Parent == nil and magnitude < 20 then gui.Parent = game.Players.LocalPlayer.PlayerGui elseif magnitude >= 20 then gui.Parent = nil end print("it just ran") wait(0.5) end
The gui still doesn't show up upon respawning until I delete and paste. However, the script does run because "it just ran" is printed in the Output. Why does it skip the if statements?
LocalScripts will only run as a descendant of the Character or the Player online -- not childs of random parts in the workspace.
That said, this worked perfectly for me.
Here is the exact code that I ran.
Player = game.Players.LocalPlayer repeat wait() until Player.Character Character = Player.Character part = workspace.Part; gui = game.ReplicatedStorage.TextLabel:Clone() while true do magnitude = (part.Position - Character.Torso.Position).magnitude if gui.Parent == nil and magnitude < 20 then gui.Parent = Player.PlayerGui elseif magnitude >= 20 then gui.Parent = nil end print(magnitude, gui.Parent) wait(0.5) end
LocalScripts run almost immediately upon readying the player for a spawn.
That means it happens before the Character
is actually loaded. If you print(Character)
I would expect you to see nil
.
You have to wait for the Character
to be loaded. You could use CharacterAdded, though I distrust it in this because it's possible the Character would load first.
The simplest solution is a simple repeat until
loop:
Player = game.Players.LocalPlayer repeat wait() until Player.Character Character = Player.Character