I’m trying to figure out a way to respawn a hat if the player wearing it leaves the game. There’s only one of the hat, so if the player leaves while wearing it, it cannot be worn again until the server is restarted.
I tried using Player.Removing to check if the player was wearing the hat and respawn it, but I can’t access the player’s character once they leave. I also tried setting an attribute (true for when it exists, false for when it doesn’t) for a folder the hat is in, but there’s no real way to set that to false from a script in the hat itself because the hat gets deleted when the player leaves. The only thing I can think of and haven’t tried yet is looping through the whole workspace and checking if it exists, but I don’t think that’d be great for optimization and could really lag the game.
Maybe try using Player.CharacterRemoving()? I meant like pairing both .CharacterRemoving and .PlayerRemoving to decide how the hat will be moved.
Bind .CharacterRemoving so that the hat will move to where the character once was.
Bind .PlayerRemoving so the hat that is now on the ground where the character last was can be moved to its original spawn (you should probably keep an array with all hats in the game like hats[Player] = Hat so you can call hats[player] to get the hat).
Wouldn’t that fire when the player dies too? I made it so when the player dies, they drop the hat where they are. If they leave, I want the hat to respawn in its spawn location.
My favourite way is with CollectionService just because it allows me to tap into an event-based workflow without doing the heavy lifting myself. You can then respawn the hat with GetInstanceRemovedSignal when the hat or its wearer don’t exist anymore.
local MY_HAT_TAG = "HasCoolCat"
CollectionService:GetInstanceRemovedSignal(MY_HAT_TAG):Connect(function (obj)
-- Assume we can respawn the hat anyway
doHatRespawn()
end)
CollectionService:AddTag(player, MY_HAT_TAG)
-- Player not in DataModel, tag is removed from player, fires tag removed
player:Kick()
If you need it to respawn when they died, add the tag to the character instead of the player.
Hold on, I know this topic is a bit old now, but how do I go about removing the tag when the character dies? I don’t want the hat to respawn when they die, but I also don’t want the tag on the Player to stay after they die.
Tags are serialised on an instance so when the character is deparented from the DataModel after death the tag will remove itself. If you need to explicitly remove a tag, check the documentation for CollectionService - RemoveTag. You’ll also need explicit differentiations between a player’s death and leaving so you can respawn the hat accordingly.