It's supposed to save a player's data when he leaves and load it when he joins.

When a player leaves the game it's supposed to save his MaxHealth and MaxKi, and when a player joins the game it's supposed to load his MaxHealth and MaxKi, but that doesn't happen.

Script:

game.Players.PlayerAdded:connect(function(player)
	local stats = Instance.new("Folder", player)
	stats.Name = "Stats"
	local hpboosters = Instance.new("NumberValue", stats)
	hpboosters.Name = "HPBoostersUsed"
	hpboosters.Value = 0
	local hpboosters = Instance.new("NumberValue", stats)
	hpboosters.Name = "KiBoostersUsed"
	hpboosters.Value = 0
	local l = Instance.new("NumberValue", stats)
	l.Name = "Level"
	l.Value = 0
	local e = Instance.new("NumberValue", stats)
	e.Name = "Exp"
	e.Value = 0
	local me = Instance.new("NumberValue", stats)
	me.Name = "MaxExp"
	me.Value = 5
end)
game.Players.PlayerRemoving:connect(function(player)
	local char = workspace:WaitForChild(player.Name, 5)
	local key = "user_" .. player.UserId
	local DataStore = game:GetService("DataStoreService")
	DataStore:GetDataStore("MaxHP"):SetAsync(key, char.Humanoid.MaxHealth)
	DataStore:GetDataStore("MaxKi"):SetAsync(key, char.MaxKi.Value)
	DataStore:GetDataStore("MaxHP"):UpdateAsync(key, function(oldValue)
		local newValue = oldValue or 100
		return newValue
	end)
	DataStore:GetDataStore("MaxKi"):UpdateAsync(key, function(oldValue)
		local newValue = oldValue or 15
		return newValue
	end)
end)
workspace.ChildAdded:connect(function(char)
	local player = game.Players:GetPlayerFromCharacter(char)
	if player then
		local DataStore = game:GetService("DataStoreService")
		local key = "user_" .. player.UserId
		print(key .. "'s data has loaded with " .. tostring(DataStore:GetDataStore("MaxHP"):GetAsync(key) or 100) .. " MaxHP and " .. tostring(DataStore:GetDataStore("MaxKi"):GetAsync(key) or 15) .. " MaxKi")
		local k = Instance.new("NumberValue", char)
		k.Name = "Ki"
		k.Value = DataStore:GetDataStore("MaxKi"):GetAsync(key) or 15
		local mk = Instance.new("NumberValue", char)
		mk.Name = "MaxKi"
		mk.Value = DataStore:GetDataStore("MaxKi"):GetAsync(key) or 15
		char.Humanoid.MaxHealth = DataStore:GetDataStore("MaxHP"):GetAsync(key) or 100
	end
end)
game.OnClose = function()
	print("Giving time for data to be saved...")
	wait(10)
	print("Done! Shutting down...")
end

I've tried putting in a OnClose callback but that didn't fix the saving and loading so i inserted the "DataStoreService" service to Studio it still didn't fix the problem so i enabled API and it still didn't work.

The "GetAsync()" function always returns null when i test in my place, i wonder how to fix this.

sorry if my english is bad and sorry if the title is not appropiate for this :/

2 comments

0

you declared 2 variables with the same name?

0

Why are you using the childAdded event to load stats? you should load them once only unless an error occurs that would require you to retry.