I followed a tutorial on YouTube learning how to write a datastore script, however, when I tested it out, it doesn't seem to work on either studio test mode or through joining the game. API services are turned on and it worked for the tutorial, but not for my script.
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 Wins = Instance.new("IntValue")
Wins.Name = "Wins"
Wins.Parent = leaderstats
-----------------------------------------------------------
local playerUserId = "Player_"..player.UserId
local data --This turns it into a more global variable.
--This will load the data, wrap it around a pcall to handle errors if any occur.
--Everytime the player joins, it will find out if the player has played the game or not or have any data stored.
local success, errormessage pcall(function()
local data = myDataStore:GetAsync(playerUserId) --You will assign the GetAsync to this variable.
end)
if success then
--This will set our data to the current amount of cash.
--After data has been defined from GetAsync, it will not equal to the cash value.
--This will set the data to its corresponding cash value.
--Since you are saving data through a table, you may not write Cash.Value = data
Cash.Value = data.Cash
Wins.Value = data.Wins
end
end)
--Save the data, you need the data before it is loaded.
--Since you don't want to save data right when the player joins, you will save it outside of the PlayerAdded event.
game.Players.PlayerRemoving:Connect(function(player)
--Save the data
--Get the player's UserId
local playerUserId = "Player_"..player.UserId
--Now instead of getting data when loading the game, you set the data when saving it
local data = {
Cash = player.leaderstats.Cash.Value; --Take the cash value from player's gui leaderstats.
Wins = player.leaderstats.Wins.Value;
}
--Before setting async, you must wrap it around a pcall to protect the player's data
local success, errormessage pcall(function()
myDataStore:SetAsync(playerUserId, data)
end)
if success then
print("Data successfully saved!")
else
warn("There was an error in saving the player's data.")
warn(errormessage)
end
end)

4 comments
ayy devking pog
any errors in the console?
Line 55, expected "=".
-1 This is caused by a typo