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

Why does this error "attempt to index a nil value"?

Can anyone tell me why output gives the error attempt to index a nil value(in the script for when it's fired)? The purpose of the script is to change someone to a team color and respawn them when they have a certain amount of deaths, but it isn't working.

Code to fire it(in a LocalScript, in StarterPack):

-- Variables
local Player = game.Players.LocalPlayer
local Stats = Player:WaitForChild("leaderstats")

if Stats["Deaths"].Value == 3 then
	game.ReplicatedStorage.RemoteEvent:FireServer(game.Players.LocalPlayer)
end

script:Destroy()

Code for when it's fired(in a ServerScript, in ServerScriptService.(this is the one that is erroring)):

game.ReplicatedStorage.RemoteEvent.OnServerEvent:connect(function(Player)
	game.Players:FindFirstChild(Player).TeamColor = game.Teams.TestTeam.TeamColor
	game.Players:FindFirstChild(Player):LoadCharacter()
end)

Any help appreciated.

1 answer

✓ Accepted answer

Try this. I also connected it to an event.

In a LocalScript:

-- Variables
local Player = game:GetService("Players").LocalPlayer
local Stats = Player:WaitForChild("leaderstats")
local Deaths = Stats:WaitForChild("Deaths") 

Deaths.Changed:connect(function (v)
    if v == 3 then
    	game.ReplicatedStorage.RemoteEvent:FireServer() -- you didn't need the argument here. FireServer() automatically provides the player as one of its arguments.
        script:Destroy() -- this should probably be inside the if-statement
    end
end)

In a Script:

game.ReplicatedStorage.RemoteEvent.OnServerEvent:connect(function(Player)
    Player.TeamColor = game.Teams.TestTeam.TeamColor
    Player:LoadCharacter()
end)

Where is the LocalScript located? If it's not already in game:GetService("StarterPlayer"):WaitForChild("StarterPlayerScripts"), then it should.

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