Stat returns to its original value before taken away

Hi! I recently implented a shop system, (thanks to the people that helped me) but something is wrong. Let’s say I buy an upgrade, it takes my currency away. Then, I go grab some more. It returns back to its original value before I bought the upgrade!

--Basically what happens if the corn is touched
local Players = game:GetService("Players")
local corn = script.Parent
local RepStorage = game:GetService("ReplicatedStorage")
local cornamountval = RepStorage:WaitForChild("cornamount")
local cornamount = game.StarterGui.cornamount.Frame:WaitForChild("cornamountlabel")
local CornHarvestEvent = RepStorage:WaitForChild("CornHarvestEvent")

corn.Touched:Connect(function(hit)	
	local player = Players:GetPlayerFromCharacter(hit.Parent)
	if player then
		corn:Destroy()
		cornamountval.Value = cornamountval.Value - 1
		local leaderstats = player.leaderstats
		local cornStat = leaderstats:FindFirstChild("corn")
		if cornStat then
			cornStat.Value = cornStat.Value + 10
		end
		CornHarvestEvent:FireClient(player)
	end
end)

Hello Omega,

The code that you provide likely isn’t the cause of the issue. The code for it looks fine.

The first half of your video shows you buying an upgrade using corn. Is your upgrade script being run by a local script? If so, your corn and upgrades haven’t been updated on the server. You would have to code the script to subtract the corn value on a server script.

2 Likes

Oh. Yeah, my upgrade script is on a localscript. I’ll go fix it now and see if it works. Thank you!

Small problem. I’m using localplayer to get my stats in the localscript, but I can’t get that in a normal script. How would I do this?

Hello Omega,

You can request to the server to buy the upgrade for you through a remote event. The request will include the player object.

-- LOCAL SCRIPT
RequestBuyUpgrade:FireServer()

-- SERVER SCRIPT
RequestBuyUpgrade.OnServerEvent:Connect(function(player)
    local leaderstats = player:FindFirstChild("leaderstats")
    -- subtract value server side
end)
2 Likes