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

How to fix index nil with leaderstats?

I want to change strength to cash when i touched a brick in the leader board,after making somethings,i have an error in the brick's script(not local script), its said index nil with leaderstats.Here i have 2 scripts:1 at sever script service:

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

local cash = Instance.new("NumberValue")
cash.Name = "Cash"
cash.Value = 0
cash.Parent = leaderstats

local strength = Instance.new("IntValue")
strength.Value = 0
strength.Parent = leaderstats
strength.Name = "Strength"
    end)

1 at the brick(Where have that error):

    local player = game.Players.LocalPlayer
    local leaderstats = player.leaderstats
    local strength = leaderstats.Strength
    local cash = leaderstats.Cash
    script.Parent.Touched:Connect(function(hit)
        if hit.Parent:FindFirstChild("Humanoid") then
	        local Player = game.Players:GetPlayerFromCharacter(hit.Parent)
	        cash.Value = cash.Value + strength.Value
	        end
        end)

Please help me if you can.

Edit:change script to local script will not work,even there is no error.

3 comments

0

You are not getting the leaderstats properly in a serverscript and it needs to be a 'script' not a local script since they only run on the client

0

Check my answer

0

I have used a script already, but it doesn't work

2 answers

✓ Accepted answer

Here you go. Make sure this is a regular script inside the brick.

script.Parent.Touched:Connect(function(hit)
    if hit.Parent:FindFirstChild("Humanoid") then
        local Player = game.Players:GetPlayerFromCharacter(hit.Parent)
        Player.leaderstats.Cash.Value = Player.leaderstats.Cash.Value + Player.leaderstats.Strength.Value
        end
    end)

Hope this helps

2 comments

0

Also keep in note that LuaU supports a shortened version of adding values, such as using += instead of writing all of that! You can shorten it down to just Player.leaderstats.Cash.Value += Player.leaderstats.Strength.Value.

0

Yes. I always use that. But since in the question, he wrote using the other way. I thought to write that in my answer as well.

For the script at the brick, use a LocalScript instead of a ServerSidedScript.

3 comments

0

Doesn't work like that.

0

I meant, if you use a ServerSidedScript instead of LocalScript, that index nil with leaderstats error will not appear. And the script may possibly work out fine

0

LocalScript instead of ServerSidedScript*, sorry

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