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

Why does my script say attempt to index nil with leaderstats?

My code is here, and I am using a script on line 20 is where the error is

local player = game.Players.LocalPlayer

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("IntValue",player)
	leaderstats.Name = "leaderstats"

	local Kills = Instance.new("IntValue",leaderstats)
	Kills.Name = "Kills"
	Kills.Value = 0

	local Deaths = Instance.new("IntValue",leaderstats)
	Deaths.Name = "Deaths"
	Deaths.Value = 0

	local Cash = Instance.new("IntValue",leaderstats)
	Cash.Name = "Cash"
	Cash.Value = 1000
end)
game.ReplicatedStorage.Bought.BoughtACR.OnServerEvent:Connect(function()
	if player.leaderstats.Cash.Value >= 1000 then -- works until here
		print("something")
		player.leaderstats.Cash.Value = player.leaderstats.Cash.Value - 1000
	end
end)

1 comment

0

Also, just an added tip, This is a server script, so you won't be able to get the "LocalPlayer" for your variable at the top.

1 answer

✓ Accepted answer

You did not define player, the OnServerEvent has a player argument by default. Starting on line 19, define player like this:

game.ReplicatedStorage.Bought.BoughtACR.OnServerEvent:Connect(function(player)
    if player.leaderstats.Cash.Value >= 1000 then -- works until here
        print("something")
        player.leaderstats.Cash.Value = player.leaderstats.Cash.Value - 1000
    end
end)

This will fix your error.

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