Wondering if this is a good datastore system?

I have made this script for saving leaderstats with datastores, and it is incredibly lightweight. However sometimes when new players join, when there is a stat that is meant to already have a set value, it is set to the default value of the value instance.

This is the script:

game.Players.PlayerRemoving:Connect(function(player)
	local datastore = game:GetService("DataStoreService"):GetDataStore(player.UserId.."Stats")

	local statstorage = player:FindFirstChild("leaderstats"):GetChildren()
	local inventorystorage = player:FindFirstChild("Inventory"):GetChildren()
	for i, v in pairs(statstorage) do
		datastore:SetAsync(v.Name, v.Value)
		print("saved "..v.Name.." "..v.Value)
	end
	for i, v in pairs(inventorystorage) do
		datastore:SetAsync(v.Name, v.Value)
		print("saved "..v.Name)
	end
end)



game.Players.PlayerAdded:Connect(function(player)
	local datastore = game:GetService("DataStoreService"):GetDataStore(player.UserId.."Stats")
	player:WaitForChild("leaderstats")
	player:WaitForChild("Inventory")
	player:WaitForChild("Inventory"):WaitForChild("Swordsman")
	
	local statstorage = player:FindFirstChild("leaderstats"):GetChildren()
	local inventorystorage = player:FindFirstChild("Inventory"):GetChildren()
	for i, v in pairs(statstorage) do			
		v.Value = datastore:GetAsync(v.Name)
	end
	for i, v in pairs(inventorystorage) do
		v.Value = datastore:GetAsync(v.Name)
	end
end)

Is this a good system? and if not what changes should I make?

Many Thanks.

1 Like

It looks pretty good. Though I’m not sure what the behavior will be due to redefining a variable for the data store every time a player joins the game. But! I’ve never tried creating a datastore for every player user id. If it works, I suppose it’s fine.