Character is nil after indexing in a PlayerRemoving connection

I am writing a code and it utilizes Players.PlayerRemoving. Whenever I attempt to index the players character in that connection, it comes out nil. How could I solve this issue? Current code sample:

Players.PlayerRemoving:Connect(function(plr)
	if plr.Character then
		print("yes")
	end
end)
1 Like

I’m not sure you can. By the time the function executed, the character is already no longer in the game.

1 Like

I don’t think you can do anything with the character, as it probably gets destroyed before the connection events get fired.

If you are trying to handle information related to the player, this is my suggestion:

I would suggest keeping it in server storage because it can’t be exploited there, as well as persisting after players leaving if you so need it. You can just make a folder when the player joins, and name it using their userid like so:

Players.PlayerAdded:Connect(function(player)
   local datafolder = Instance.new("Folder")
   datafolder.Parent = game:GetService("ServerStorage") -- this could also be a folder in server storage, just add a findfirstchild or waitforchild afterwards
   datafolder.Name = player.UserId .. "-Data"
   --rest of code for adding information to folder here
end

And to remove this folder on players leaving you just find it in the server storage and call :Destroy() on it. If you didn’t want it removed on player removing, you could just hold a table of playerids of players that left and when you need to remove the folders you could go through that table of playerids and remove the appropriate folders, clearing that table when you do so.

If its something other than information related to the player, I wasn’t able to think of a solution other than maybe trying to use a model that isn’t tied to the player like their character is (e.g. make a model in the workspace that is separate from their character, but move that model to the players humanoidrootpart).


Hope this helps!

3 Likes

I modified your code and it works. I just stored the character data in a folder and when the playerremoving connection is fired I just grab the data and use it.

1 Like