Issues with my DataStore

Hello, ive been learning datastore and tried creating a simple little game with using it. However, when a player joins, the data comes back as nil. Also, when the data is saved, nothing after the SetAsync continues to process.

local DDS = game:GetService("DataStoreService")
local DataStore = DDS:GetDataStore("Inventory")

local DefaultInventory = {
				Mutton = 0,
				Steel = 0,
				Gold = 0,
				Tools = {"CommonSword"},
				Consumables = {"Health+"},
				Equipment = {"WoodArmor"},
				Pets = {}}

game.Players.PlayerAdded:Connect(function(player)
	local stats = Instance.new("Folder",player)
		stats.Name = "leaderstats"
		
		local Mutton = Instance.new("IntValue",stats)
			Mutton.Name = "Mutton"
		local Steel = Instance.new("IntValue",stats)
			Steel.Name = "Steel"
		local Gold = Instance.new("IntValue",stats)
			Gold.Name = "Gold"
			
	
		local Inventory
	local Recieved, Result = pcall(function()
		 Inventory = DataStore:GetAsync(tostring("Player_"..player.UserId))
	end)
	if Recieved then
		print("Success")
		if Result ~= nil then -- data is always nil
			print("Found Data")
			player.leaderstats.Mutton.Value =Inventory.Mutton
			player.leaderstats.Steel.Value = Inventory.Steel
			player.leaderstats.Gold.Value = Inventory.Gold
		else
			print("Need Data")
			local passed, errormessage = pcall(function()
				DataStore:SetAsync(tostring("Player_"..player.UserId),DefaultInventory)
			end)
			if passed then
				print("Set Default")
			else
				print("Failed")
			end
		end
	else
		player:Kick("Data Error. Please Rejoin.")
	end
	
	
end)

game.Players.PlayerRemoving:Connect(function(player)
	
	local DataForStore = {}
	DataForStore = DefaultInventory
	
	local passed , errormessage = pcall(function()
		DataStore:SetAsync(tostring("Player_"..player.UserId), DataForStore)
		print("Saved") -- This is where it stops proccessing. Not even the print is displayed.
	end)
	if passed then
		print("Saved Data")
	elseif errormessage then
		print("Error: Did Not Save")
	end
	print("End")
end)
2 Likes

You don’t really need tostring for a datastore.
In addition, this line isn’t needed

if Result ~= nil then

Instead, replace that line with this line:

if Inventory then

Because Inventory is where the data is stored. You can use the second parameter in a pcall, but the second parameter is never nil, it’s either an error, or an object.

Wow, i feel special haha. This worked, thank you so much!

1 Like