Datastore failing to save

I am super new to datastoreservice and trying my best to understand and learn it for future projects
(I might move to profileservice but I want to learn datastoreservice first)

I looked everywhere to try to find a solution but all seems very similar to my script yet it doesn’t work

local DataStoreService = game:GetService("DataStoreService")
local StageData = DataStoreService:GetDataStore("StageData")
local ServerStorage = game:GetService("ServerStorage")
local Players = game:GetService("Players")

function PlayerAdded(Player)
	local Character = Player.Character or Player.CharacterAdded:Wait()
	
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = Player

	local Stage = Instance.new("IntValue")
	Stage.Name = "Stage"
	Stage.Parent = leaderstats
	
	local Success,Returned = pcall(function()
		StageData:GetAsync(Player.UserId)
	end)
	
	if Success and Returned then
	    print(Returned)
	else
		print(Returned)
	end
	
end

function PlayerRemoved(Player)
	local PlayerData = {
		Stage = Player.leaderstats.Stage.Value,
		
	}
	StageData:SetAsync(Player.UserId,PlayerData)
	warn("Updated Player Data")
end

game:BindToClose(function()
	for i,v in game.Players:GetPlayers() do
		task.spawn(function()
			PlayerRemoved(v)
		end)
	end
	task.wait(3)
end)

Players.PlayerAdded:Connect(PlayerAdded)
Players.PlayerRemoving:Connect(PlayerRemoved)

This setup is very similar to what all people suggests and how they do it but for some reason
Returned variable is always nil
I have tried in studio and in my game but still returning nil at all times

I am confused on why this happens I tried looking for tutorials in case I did something wrong but most have the same setup
I would really appreciate any help

You’re doing this:

But since you’re not returning the result of GetAsync, the returned variable will always be nil.

To fix this, you need to return the value inside the pcall function:

local Success,Returned = pcall(function()
	return StageData:GetAsync(Player.UserId)
end)

This way, returned will contain the data from GetAsync if it was successful.

5 Likes

Yep that was the issue as I said I am not very used to datastoreservice nor I am used to having two variables assigned to one value thanks for your help

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.