Can't save something to Datastore

You’re attempting to save a folder to a data store, and that isn’t possible. What you should do is store a dictionary of all the data to be saved.

local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local HatsDataStore = DataStoreService:GetDataStore("Hats")

Players.PlayerAdded:Connect(function(player)
	
	local hats = Instance.new("Folder", player)
	hats.Name = "Hats"
	
	local data = nil
	local success, err = pcall(function()
		data = HatsDataStore:GetAsync(player.UserId.."-hats")
	end)
	
	if success then
		
		if data then -- handle whatever you'd like here and load the existing data
			
		else -- handle what to do when a player has joined for the first time
			
		end
		
	else
		warn("There was an error whilst getting hat data!")
		warn("Error:", err)
	end
	
end)

Players.PlayerRemoving:Connect(function(player)
	
	local hats = {
		-- save a reference to the hat here to be loaded in later
	}
	
	local success, err = pcall(function()
		HatsDataStore:UpdateAsync(player.UserId.."-hats", function()
			return hats -- saves the hat data
		end)
	end)
	
	if success then
		print("Hats saved successfully.")
	else
		warn("There was an error whilst saving hats!")
		warn("Error:", err)
	end
	
end)

The video @Giggio450BR linked at [UNSOLVED] Can't save something to Datastore would help you to learn how to save stuff that aren’t values. StringValues, IntValues, etc…

So, the output is saying that the hats have saved, but I rejoin the game and the hat that I wore before leaving the game did not save.

Did you leave a reference to the hat, so it could be loaded later?

You’ll have to serialize the hat as you can’t just save a hat instance. My code is meant to be a guide, not the answer.

You’ll have to figure out the actual mechanics of the save for yourself, as what you’re trying to do is save an instance, then load it. The saving tools video should help you out a lot.

Data is nil. Instead do data = nil that way it wont return a error.

There is no difference between creating a variable with nothing assigned to it, and explicitly declaring a variable as nil.


local var1
local var2 = nil

-- there is no difference in type between the 2, but in my opinion explicitly setting a variable as nil looks cleaner. 

Again, there is no functional
difference between the two.