Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Localscript breaks when player resets?

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

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

3 comments

0

But what about line 2?

0

There is no need to wait for the client's character in my script. It checks to see if they have a character.

0

Oh, I see what you meant. I made it keep reference to the script's former parent. Thank you for mentioning it.

This discussion is preserved as it was. New answers, comments, and votes are closed.