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

Localscript breaks when player resets?

Asked by 9 years ago

I have a LocalScript inside a TextLabel which is a descendant of PlayerGui that constantly checks if a player has a certain tool in their inventory. The script itself works fine, however, when the player resets or dies, the script breaks. The output says: ":7: attempt to index a nil value.

The output is basically saying after the player respawns, the LocalPlayer is nil. But, there's a line of code that's supposed to prevent that.

repeat wait() until game.Players.LocalPlayer
repeat wait() until game.Players.LocalPlayer.Character

while wait() do
    if game.Players.LocalPlayer then
        local get = game.Players.LocalPlayer
        local backpackgun = game.Workspace:findFirstChild(get.Name):findFirstChild("Long Bow")
        local gun = get.Backpack:findFirstChild("Long Bow")
        if not gun and not backpackgun and script.Parent.Text == "WEAPON OWNED" then
            script.Parent.Text = "BUY?"
        end
    end
end

Can anyone help me out?

EDIT: I changed the script to this:

repeat wait() until game.Players.LocalPlayer
repeat wait() until game.Players.LocalPlayer.Character

while wait() do
    if game.Players.LocalPlayer and game.Players.LocalPlayer.Character then
        local get = game.Players.LocalPlayer
        local backpackgun = game.Workspace:findFirstChild(get.Name):findFirstChild("Long Bow")
        local gun = get.Backpack:findFirstChild("Long Bow")
        if not gun and not backpackgun and script.Parent.Text == "WEAPON OWNED" then
            script.Parent.Text = "BUY?"
        end
    end
end

but the output stays the same and the script breaks.

2 answers

Log in to vote
0
Answered by
Diitto 230 Moderation Voter
9 years ago

Well, when you die, the script errors because it can't find your character, not your player.

wait();
local Parent=script.Parent;--// Former index.
script:destroy();--// Prevents removal of the script when you die.
local Player=game:service'Players'.localPlayer;
while wait() do
        local backpackgun = Player.Character and Player.Character.Parent==workspace and Player.Character:findFirstChild("Long Bow");
    local gun = get:findFirstChild'Backpack' and get.Backpack:findFirstChild("Long Bow");
    if not gun and not backpackgun and script.Parent.Text == "WEAPON OWNED"  then
        Parent.Text = "BUY?";
    end
end

0
But what about line 2? ZeptixBlade 215 — 9y
0
There is no need to wait for the client's character in my script. It checks to see if they have a character. Diitto 230 — 9y
0
Oh, I see what you meant. I made it keep reference to the script's former parent. Thank you for mentioning it. Diitto 230 — 9y
Ad
Log in to vote
0
Answered by 9 years ago

I updated the script; look at my first post.

Answer this question