Datastore script error

I do not know why my script is not working, can you please help?
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 gold = Instance.new("IntValue")
gold.Name = "Gold"
gold.Parent = leaderstats

local playerUserId = "Player_"..player.UserId

myDataStore:GetAsync(playerUserId)

--Load Data--
local data
local success, errormessage = pcall(function()
	data = myDataStore:GetAsync(playerUserId)
end)

if success then
	gold.Value = data.Gold
	--Set our data equal to the current values--	
end

end)

game.Players.PlayerRemoving:Connect(function(player)
local playerUserId = “Player_”…player.UserId

local data = {
	Gold = player.leaderstats.Gold.Value;
}

local success, errormessage = pcall(function()
	myDataStore:SetAsync(playerUserId, data)
end)

if success then
	print("Data Saved Successfully")
else
	print("error")
	warn(errormessage)
end

end)

When it says

if success then
   gold.Value = data.Gold
end

Try putting,

if success then
   gold.Value = data
end

The reason you put

gold.Value = data

is because there is no Gold child in the datastore. The datastore is only saving the gold’s value or the integer value. So as a result, you set it to data itself, not data.Gold.

Hopefully, this helps you.

Roblox has recently been having data store issues, its mostly resolved now but it could be effecting your script.

Please make sure to correctly post scripts.
Here is what I tried doing:

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 gold = Instance.new("IntValue")
   gold.Name = "Gold"
   gold.Parent = leaderstats

   local playerUserId = "Player_"..player.UserId

   --Load Data--
   local data
   local success, errormessage = pcall(function()
      data = myDataStore:GetAsync(playerUserId)
   end)

   if success then
   	   gold.Value = data["Gold"]
	   --Set our data equal to the current values--	
   end

end)

game.Players.PlayerRemoving:Connect(function(player)
   local playerUserId = "Player_"..player.UserId

   local data = {
	   "Gold" = player.leaderstats.Gold.Value;
   }

   local success, errormessage = pcall(function()
	   myDataStore:SetAsync(playerUserId, data)
   end)

   if success then
	   print("Data Saved Successfully")
   else
 	   print("error")
   	   warn(errormessage)
   end

end)

Let me know if it works.

1 Like