Hi, I’v tried to make it so everytime the player dies, they lose between 5 and 30 coins but the problem is that I keep getting those “index nil” erros on my leaderstat code in line 8. Take a look at my script.
local Players = game:GetService("Players")
game:GetService('Players').PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(character)
character:WaitForChild("Humanoid").Died:Connect(function(died)
local fine = math.random(5,30)
local player = Players:GetPlayerFromCharacter(died)
local leaderstats = player.leaderstats --Error located
local coins = leaderstats and leaderstats:FindFirstChild("coins")
if coins.Value <= fine.Value then
coins.Value = 0
else
coins.Value=coins.Value-fine.Value
end
end)
end)
end)
To fix your issue, make a local script, and check when the current player died, once they died call a remote event that subtracts the coins:
Local Script
local player = game.Players.LocalPlayer
local char = game.Workspace[player.Name]
local remoteEvent = game.ReplicatedStorage.Event
char.Died:Connect(function()
remoteEvent:FireServer()
end)
Server Script:
local remoteEvent = game.ReplicatedStorage.Event
remoteEvent.OnServerEvent:Connect(function(player)
local fine = math.random(5,30)
local leaderstats = player.leaderstats --Error located
local coins = leaderstats and leaderstats:FindFirstChild("coins")
if coins.Value <= fine.Value then
coins.Value = 0
else
coins.Value=coins.Value-fine.Value
end
end)
To fix this you could just take the “player” value which you get when the player joins the server and use that as the player. There is no real need for you to find the player from the character.
Also not sure why but an extra thing is that there is no need getting the service “Players” again when the player is added when you define it above already.
I think it should be fine even inside of a server script. If you look at “Humanoid.Died” the example is a server script and is the exact code they have there so it should work fine.
With the code you posted there is a high vulnerability with an exploiter abusing because they can fire the remote event as much as they want and get a ton of coins and there is no need to use remote events as I stated cuz it should work fine just on server.
1.No need to call game:GetService('Players') again, you’ve defined it as a variable above.
2. local player = Players:GetPlayerFromCharacter(died), you’re naming this variable in the same name as the player param in the PlayerAdded event. This can cause a confusion.
3.Instead of this line - local coins = leaderstats and leaderstats:FindFirstChild("coins")
you can simply do - local coins = leaderstats:FindFirstChild("coins")