Data store, trash

local datastoreservice = game:GetService("DataStoreService")
local mystore = datastoreservice:GetDataStore("mydatastore")

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

	local coins = Instance.new("IntValue", ld)
	coins.Name = "Coins"
	coins.Value = 0

	local playerid = "Player_" .. player.UserId
	local data = mystore:GetAsync(playerid)

	if data then
		coins.Value = data["Coins"]
		print("Data Loaded", data, data["Coins"])
	else
		coins.Value = 1
		print("ELSE")
	end
	

	coins.Changed:Connect(function(newValue)
		local datatobesaved = {
			Coins = newValue
		}
		local success, err = pcall(function()
			mystore:SetAsync(playerid, datatobesaved)
		end)
		if success then
			print("Data saved!")
		else
			print("Data failed to save:", err)
		end
	end)
end)


game.Players.PlayerRemoving:Connect(function(player)
	local datatobesaved = {
		Coins = player.leaderstats.Coins.Value;
	}
	local playerid = "Player_" .. player.UserId
	local success, err = pcall(function()
		mystore:SetAsync(playerid, datatobesaved)
	end)
	if success then
		print("data saved!")
		print(player.leaderstats.Coins.Value)
	else
		print("data faield to save!")
	end
end)

Here is the script, the most basic, when I go into the game there is a change in explorer, coins to 100 then correctly go into the game. And again I see 1, although I changed.

There are no errors, in the settings allowed all, here are the prints:

Did you change the value from the client or the server? Any changes from the client won’t replicate to the server.

I change value from explorer,

here

Yes, but is the environment the client (default when you start the game as a player), or the server (highlights the viewport with a green border)? You can change it with this button:
image

1 Like

Okay, but if I want to change coins by clicking on the button. it should be done through events?

Can I create a module function and call it to change coins? Will it work then

Yes, you can also create a button that lets you change coins as the player, using a RemoteEvent to tell the server when the player clicks the button on the client.

okay, but can I use module function?

Like this:
Module:

function coinModule.GiveCoins(player)
	local data = player:WaitForChild("Data")
	local ld = player:WaitForChild("leaderstats")
	local bunkCoins = data:WaitForChild("BunkCoins")
	bunkCoins.Value = bunkCoins.Value + 10
end

Local:

clickButton.MouseButton1Click:Connect(function()
		CoinModule.GiveCoins(player)
end)

You’ll still need a RemoteEvent to tell the server to run that module’s function, because running it from the client will still only change it on the client, not the server.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.