DataStore not working

  1. What do you want to achieve? Keep it simple and clear!

A working data store that saves Cash.

  1. What is the issue? Include screenshots / videos if possible!

The code has no errors yet it is not working properly.
image

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

I’ve tried looking over and over the API reference and couldn’t find anything wrong. I’m not sure if it is a spelling error but I just can’t find it

local DataStoreService = game:GetService("DataStoreService")
local myDataStore = DataStoreService:GetDataStore("myDataStore")

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local Cash = Instance.new("IntValue")
	Cash.Name = "Cash"
	Cash.Parent = leaderstats
	
	local playerUserId = "Player_"..player.UserId
	
	--Load data
	local data
	local success, errormessage = pcall(function()
		data = myDataStore:GetAsync(playerUserId)
	end)
	
	if success then
		Cash.Value = data
	end
	
	
end)


game.Players.PlayerRemoving:Connect(function(player)
	local playerUserId = "Player_"..player.UserId
	
	local data = player.leaderstats.Cash.Value
	
	local success, errormessage = pcall(function()
		myDataStore:SetAsync(playerUserId, data)
	end)
	
	if success then
		print("Data successfully saved!")
	else
		print("There was an error.")
		warn(errormessage)
	end
end)

If anyone can help me find out what’s wrong, it would be appreciated.

You are making data a Boolean when you say local data correct?

I would try local data = 0 since right now you are just pretty much saying local data

I was trying to get local data out of a scope so I could use it across the entire script if that makes sense.

Edit: Setting local data to 0.

1 Like

Are you testing this through Studio or the Game?

Studio. May that be the problem instead?

I would change this to this. To check if there is any current data.

if success then
	Cash.Value = data
else
    print("Data not found")
end

Everything else looks good. Make sure you have API Services allowed.

1 Like

Even so, when ran it will not print Data not found neither save my data. image

1 Like

I ran it in studio and it has printed for me image
Reset the data store key and try again. I will test in-game and see if it works.

(make sure you change cash server-sided and not locally)

Yes, I have changed my cash server sided in studio. I will try resetting the data store key.

1 Like

After testing in a game, it works. Always make sure to test in game. Happens a lot to me.

2 Likes

If you are testing in studio, it’s advised to use a bindtoclose function.

2 Likes

This has started to work thank you for helping me! I created a new game to override to reset the data store key and turned on ‘access to API services’. Thank you.

1 Like