Hi, this is my first post on the dev forum so I’m sorry if this is a little unclear. I am trying to achieve a position-saving system that saves your current position every time you leave the game.
My current issue is that although it works, sometimes when I leave the game I get the error, attempt to index nil with HumanoidRootPart. I suspect this error is because I have the code run on a playerRemoving function and I suspect the character and Humanoid root part has already left the game by the time I ran the code.
Players.PlayerRemoving:Connect(function(player)
local profile = Profiles[player]
if profile.Data.CurrentlyLoaded == false then
return
elseif profile.Data.CurrentlyLoaded == true then
print(player.Character.HumanoidRootPart.Position)
profile.Data.Cframe.Position.x = player.Character.HumanoidRootPart.Position.x
profile.Data.Cframe.Position.y = player.Character.HumanoidRootPart.Position.y
profile.Data.Cframe.Position.z = player.Character.HumanoidRootPart.Position.z
profile.Data.CurrentlyLoaded = false
print(profile.Data.Cframe.Position)
end
if profile ~= nil then
profile:Release()
end
end)
I have searched far and wide and couldn’t find anyone with the same problem as me. Please help me out. Thank you! Some people were telling me that it is a vector 3 issue but I assure you it is not as it has worked before and it still works now but it is not 100% reliable as I randomly receive this error. the profile.data.cframe uses the profile service data module for data stores. If you don’t know what that is just imagine that I’m saving the humanoidrootpart position to a global variable that saves after you leave the game.
It might be that by the time the PlayerRemoving event fires, the Character has already been removed from the game, so it fails. You try linking it to the CharacterRemoving event instead.
Hello, I’ve fixed your issue along with optimizing it a bit. Hope this helps.
Players.PlayerRemoving:Connect(function(player)
local profile = Profiles[player]
if profile and profile.Data.CurrentlyLoaded and player.Character then
local HumanoidRootPart = player.Character:FindFirstChild("HumanoidRootPart")
if HumanoidRootPart then
local position = HumanoidRootPart.Position
print(position)
profile.Data.Cframe.Position = position
profile.Data.CurrentlyLoaded = false
print(profile.Data.Cframe.Position)
end
profile:Release()
end
end)
Sorry, But if you’re still not getting the Position to be printed, then the script can’t find either the Profile or Profile.Data.CurrentlyLoaded, or Player.Character. Which means the issue is somewhere else in the game. Most likely the ‘Profiles[player]’.
apparently, the players’ character is nil. This is the most confusing yet because the player is already loaded in I know that for a fact so I have no idea why it wouldn’t be loaded in.