Issue with saving data

To begin, I cannot describe how annoying this issue is due to the fact that I changed literally nothing and am getting errors even in studio after testing in-game. Basically trying to save the characters position using the following code:

function SaveData(player)
	local UUID = player.UserId
	local Data = LivePlayerData[UUID]
	local Serialized = {player.Character.HumanoidRootPart.CFrame:GetComponents()}
	
	local TableToSave = {
	
		SpawnPosition = Serialized
	}
	local success, err = pcall(function()
		DS_MainDataStore:SetAsync(UUID, TableToSave)
	end)
	
	if success then
		warn("DATA SAVED")
	else
		
		warn("DATA DID NOT SAVE!")
	end
end

I keep getting the following error: attempt to index nil with 'HumanoidRootPart which is in reference to line 4 of this script. First I would rather just save the serialized value to a table then save that table after rather than waiting for the character, but I was unable to get this to work. Additionally I am 100% certain the character exists, unsure what changed because one moment it was working then after trying in-game it appears to have broken the entire thing including in studio.

Update: I should mention, SaveData() is being called when the player is leaving on PlayerRemoving.

player.Character is client sided reference, Server views that value as nil. Use workspace[player.Name] instead, should fix your issue :+1:

Seems like the player’s character has already been removed from the workspace. You could try utilising the CharacterRemoving event and getting the data to save there.

This is incorrect. The Character of a player is a property within their player object. You can reference it from the server - I have many server-sided scripts that do that myself. I’m pretty sure PlayerRemoving fires after CharacterRemoving, so in this case, the character is already gone from the workspace.

Record position data for every CharacterRemoving event. Save position data on PlayerRemoving

CharacterRemoving Could be useful however it raises issues, I need to be able to determine the difference between a player simply respawning or a player leaving as the spawn behaviour between both actions is significantly different. ( In terms of how the game functions i.e where they spawn )

The main idea is to save the players location and then load it if they leave / rejoin, but to spawn them at preset places if they reset.

I am considering binding an event to the reset button and only calling my behaviour for respawning at a set location based off of that reset, but this would still have issues with the location saving due to the character removing.

Just make it so that whenever the CharacterRemoving event fires, store the info in the desired data type in a value under the player. Then, read from this value when saving.

This suffers from the same issue mentioned above which is, if I call CharacterRemoving; it will apply for both a RESET and the CHARACTER LEAVING. if I were to save the data for the last location before a reset, then act upon it, I would spawn where I reset which is not the intended behaviour. please correct me if I am wrong on this though I appreciate all support.

I should add, the intended behaviour is that when you leave the game, your location is saved so that when you rejoin you will spawn exactly where you left off. This is different to a reset which should spawn you at a spawnpoint or ideally run its own function.

Yeah, CharacterRemoving would fire on all of these occasions, where leaving would be the last. If the player reset and then left before respawning, they would not have anywhere to respawn - therefore causing an error.

By writing to a value (NOT the store) on all occasions, then writing the last value to the store, you are effectively saving their last location and providing a backup.

I will attempt to implement this and get back to you on it.

How would I save the CFrame value to the datastore?

use json encode with http service and encode the CFrame:GetComponents()

function SpawnHandler:SaveSpawnPos(player, datatable)
	local UUID = player.UserId
	local SavedPosition = datatable[UUID]["CharacterData"]["SpawnData"].SavedPosition
	local Character = player.Character
	local cfr = EncodeCFrame(Character.HumanoidRootPart.CFrame)
	local Encoded = game:GetService("HttpService"):JSONEncode(cfr)
	SavedPosition = Encoded
	print(SavedPosition)
	print(Encoded)
	
end

I keep running into the same error which is: attempt to index nil with 'HumanoidRootPart'

This function is being called immediately upon CharacterRemoving being fired so by the time it gets around to this the character is already gone? I am unsure how to fix this

May have found a solution, instead of getting Character via player.Character which doesn’t seem to work, I’m instead ( should of from the start ) passing the character object from the character removing, this appears to work. Will update once I fix the json setup.

function SaveData(player)
	local UUID = player.UserId
	local Data = LivePlayerData[UUID]
	local Character = player.Character or player.CharacterAdded:Wait()
	local Serialized = {Character.HumanoidRootPart.CFrame:GetComponents()}
	
	local TableToSave = {
	
		SpawnPosition = Serialized
	}
	local success, err = pcall(function()
		DS_MainDataStore:SetAsync(UUID, TableToSave)
	end)
	
	if success then
		warn("DATA SAVED")
	else
		
		warn("DATA DID NOT SAVE!")
	end
end

this waits until the player has a character instance.

I want to avoid having :Wait() in my save function

Try this; I’m curious to see if it will work. It’s a weird method to write to two character arrays and encode the player’s position in advance.

local Characters = {}
local LastCharacterPoints = {}

-- Encode CFrame
local function CFrameToArray(CoordinateFrame: CFrame)
	return {CoordinateFrame:GetComponents()}
end

-- Decode CFrame
local function ArrayToCFrame(k: {number})
	return CFrame.new(table.unpack(k))
end

function SaveData(Player)
	if LastCharacterPoints[Player.UserId] then
		local UUID = Player.UserId
		local Data = LivePlayerData[UUID]
		local Serialized = LastCharacterPoints[Player.UserId]

		local TableToSave = {
			SpawnPosition = Serialized
		}
		print(TableToSave)
		local success, err = pcall(function()
			DS_MainDataStore:SetAsync(UUID, TableToSave)
		end)

		if success then
			warn("DATA SAVED")
		else

			warn("DATA DID NOT SAVE!")
		end
	else
		warn("Couldn't find player's Character in dictionary")
	end
end

local function OnPlayerAdded(Player)
	Player.CharacterAdded:Connect(function(Character)
		Characters[Player] = Character
	end)
end

local function OnPlayerLeft(Player)
	if Characters[Player] then
		LastCharacterPoints[Player.UserId] = CFrameToArray(Characters[Player].HumanoidRootPart.CFrame) 
	end
	SaveData(Player)
end

game.Players.PlayerAdded:Connect(OnPlayerAdded)
game.Players.PlayerRemoving:Connect(OnPlayerLeft)

Having a completely different issue, managed to solve the original one but this still fits under the topic I suppose, basically the issue is: If a single player is in-game, it will work perfectly, but once another player joins the code basically breaks without error.

After doing some testing, I believe the issue is to do with the saving of data, specifically if a new user joined while another was in-game it will always declare that no data exists for that player, and upon leaving and rejoining nothing for that user saves.

Trying with an account with known data, again when there is already one player in-game it causes the save to not run. I am going to add prints to see what lines these are running up to but again no errors. I will also provide a code example shortly.