Search code examples
luaroblox

Leaderstat value addition is reverted


What is supposed to happen: Randomiser adds number between 1-5 to 'money' and when clicked on imagegui it adds 500 to total

What is it actually doing: Randomiser adds number between 1-5 to 'money' and when clicked on imagegui it adds 500 to total. Then when Randomiser adds again it takes the 500 away again.

The script controlling it:

--Add money to balance on purchase
Cash500.MouseButton1Click:Connect(function()
    print("Received")--Tests to see if function works 
    game.Players.LocalPlayer.leaderstats.Money.Value = game.Players.LocalPlayer.leaderstats.Money.Value + 500
end)

**The leaderstat Handler too: **

game.Players.PlayerAdded:Connect(function(player)

    local leaderstats = Instance.new("Folder", player)
    leaderstats.Name = "leaderstats"

    local Money = Instance.new("IntValue", leaderstats)
    Money.Name = "Money"
    
    local Gems = Instance.new("IntValue", leaderstats)
    Gems.Name = "Gems"
end)

local function addTime(player)
    while true do 
        local RandomNumber = math.random(1,5)
        print(RandomNumber)
        wait(3)
        player.leaderstats.Money.Value = player.leaderstats.Money.Value + (RandomNumber)
    end
end

game.Players.PlayerAdded:Connect(addTime)

How to fix this?


Solution

  • The behavior you're getting is beause of the way clients and the server communicate. LocalScripts control the client, whereas a regular Script controls the server.

    In the client, you set the player's money. However, the client will only affect what the client sees, nothing replicates to the server. Thus, the server is unaware of what the client has done. Only the player's client believes that the money changed.

    What the server does, however, does replicate to all clients. Your server script adds a small amount of money every 3 seconds. The server is never informed about the changes the client makes to itself, so it doesn't think that the money changed. It adds to the amount it knows, which is the amount without the 500 added. Then, this change in the server replicates to all clients, reverting the addition of 500 in the client.

    You will need to use Remote Events. However, please make sure that the RemoteEvent is safe - if you make a Remote Event that gives the player money, this is unsafe since an exploiter can fire the event to get infinite money.