My Datastore script have a problem

Hi, I writing data script for my game but there a problem
When the player joined the game first time i write it give starter stats
But When second time i joined the all data is 0
Like this

Here my script

local datastoreservice = game:GetService("DataStoreService")
local LevelsDataStore = datastoreservice:GetDataStore("myDataStore")
game.Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		local data = LevelsDataStore:GetAsync(player.UserId)
		local StarterData = {
			["Level"] = 1;
			["Strenght"] = 10;
		}
		
		local blocking = Instance.new("NumberValue")
		local folder = Instance.new("Folder")
		folder.Name = "Stats"
		folder.Parent = player
		blocking.Parent = character
		blocking.Name = "Blocking"
		local level = Instance.new("NumberValue")
		level.Parent = folder
		level.Name = "Level"
		local Strenght = Instance.new("NumberValue")
		Strenght.Parent = folder
		Strenght.Name = "Strenght"
		local DataNow = {
			["Level"] = data;
			["Strenght"] = data;
		}
		if LevelsDataStore:GetAsync(player.UserId) ~= nil then
			print("Player Already Have Data")
		else
			level.Value = StarterData["Level"]
			Strenght.Value = StarterData["Strenght"]
			print("Sucess Gived Default Data")
		end
		game.Players.PlayerRemoving:Connect(function(player)
			DataNow["Level"] = level.Value
			DataNow["Strenght"] = Strenght.Value
			LevelsDataStore:SetAsync(player.UserId, DataNow)
			print("Saved Sucess")
		end)
	end)
end)

Sorry for bad grammar

You never loaded the data. You only saved it:

if LevelsDataStore:GetAsync(player.UserId) ~= nil then
    print("Player Already Have Data")
    --> Where did you load the data after checking it is saved?

Loading:

local loadedData = LevelsDataStore:GetAsync(player.UserId) --> Getting data
if loadedData then --> Checking if it exists
    print("Player Already Have Data")
    level.Value = loadedData["Level"] --> Setting the level
    Strenght.Value = loadedData["Strenght"] --> Setting the strenght

You should also handle error checking with the use of pcall (in case something goes wrong), but, for simplicity, this code is sufficient (for now).

1 Like