How do i add another value to my datastore?

  1. What do you want to achieve? Keep it simple and clear!
    My goal is to have my coins leaderstat save along with my characters
  2. What is the issue? Include screenshots / videos if possible!
    Currently i made this script below to save my characters players bought, this works fine. But i cant find myself also adding a leaderstat value to save.
  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    Ive tried a few video’s on YT, and some articles on the Devforum but none helped fixing my problem.
local function playerRemoving(player)
	local _characters = {}
	
	local succes, err = pcall(function()
		
		for i,v in pairs(player.CharacterShop.Characters:GetChildren()) do
			table.insert(_characters, v.Name)
		end
		
		task.wait(1)
		datastore:SetAsync(player.UserId.."Characters", _characters)
	end)
	
	if succes then
		print("Succes!")
	else
		warn("Error")
	end
end

Hey there,

there are multiple ways of doing what you want:

  1. Have only 1 DataStore for all the data you need structured by a table,
local Data = {
   Characters = {...}
   Coins = 0;
   Gems = 0;
   --And whatever else you need to add
}
  1. Have multiple DataStores for everything and save data into it as you’re doing right now, which means you’d have to create another DataStore or create new key for ex. player.UserId.."Coins"

The first option is probably the best as you don’t spam data into different data stores and is more efficient to save into / load from.

1 Like

Hey there, sorry for my late response but i wasnt home during christmas :slight_smile:

I’ve tried it out but i cant get it to work, ill provide details on what i tried:

Heres the code:

	local data = nil
	
	local succes, err = pcall(function()
		data = datastore:GetAsync(player.UserId,data)
	end)
	
	if succes and data ~= nil then
		for i, v in pairs(data[2]) do
			local newVal = Instance.new("StringValue")
			newVal.Name = v
			newVal.Parent = ownedCharacters
			
			coins.Value = data[1]
		end
	else
		warn(err)

	end
	
end)

local function playerRemoving(player)
	local data = {}
	
	local succes, err = pcall(function()
		
		table.insert(data, player.leaderstats.Coins.Value)
		
		for i,v in pairs(player.CharacterShop.Characters:GetChildren()) do
			table.insert(data, v.Name)
		end
		
		task.wait(1)
		datastore:SetAsync(player.UserId, data)
	end)
	
	if succes then
		print("Succes!")
	else
		warn("Error")
	end
end

And heres the error im getting:

1 Like

No problem man!

Are you sure that the data table has more than 2 elements? It seems like you’re trying to get an element (data[2]) that doesn’t exist. Make sure to check if it exists first, because if the key doesn’t exist in the datastore or there has been a change in the structure of the table, it will be saved as nil (doesn’t exist).

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