I need to run some scripts on the player’s character when he is leaving, but the problem is that PlayerRemoving always returns Player.Character = nil
The character is removed before the player leaves. Thats the reason.
But it might be possible or not depinding of what you are wanting to do
What do you need to do with the character when they leave?
Is there a way I could see when the character is getting removed/unloaded instead?
Wiki Information:
This should be what you need.
Does this invoke when a player has died and is loading a new character or only once he is leaving the game?
CharacterRemoving happens whenever a Player’s character is removed, either when they are about to respawn, or they leave the game.
There’s no reason you can’t store the character, though, and then do your work after they leave.
The following only works if CharacterRemoving always fires before PlayerRemoving. I’m not sure if that’s true.
local characters = {} -- map from players to characters
local players = game.players
players.PlayerAdded:Connect(function(player)
player.CharacterRemoving:Connect(function(character)
characters[player] = character
end)
end)
players.PlayerRemoving:Connect(function(player)
local character = characters[player]
if character then
-- do whatever you want to their character
-- note: their character's Parent will be nil and Locked here, but it's
-- hierarchy should all still be the same as it was.
characters[player] = nil -- could probably also just make characters a weak-keyed table but this works too
end
end)
Its a great idea but that script would result in a number of errors.
1.you would have to store a clone of the character
2. the char cframe would have to be constantly stored for this to work
3. when swapping out the clone the animation might need time to load
I do like the idea. but there would be a lot more to it
- No, you’re storing a reference to the last-destroyed character. No clone is made, and the reference is dropped when the player leaves.
- The CFrame of
characters[player]
would be whatever the CFrame was at the time of destruction. Also, OP never mentioned CFrame, why do you need it? - I don’t swap anything out, I’m not sure what you mean. Also, OP said they just need to run some scripts on the character when the player leaves. Not sure how animations are relevant here.