Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do I remove hats from players when they die?

local Rep = game:GetService("ReplicatedStorage")
local Remote = Rep.Events.Data.DataRemote
local Hat = Rep.ClownHat

local HatCopy = Hat:Clone()
local char

Remote.OnServerEvent:Connect(function(plr, msg)
	if msg == "hat" then
		char = plr.Character
		local Hum = char:WaitForChild("Humanoid")
		
		Hum:RemoveAccessories()
		
		char:WaitForChild("Humanoid").Died:Connect(function()
			Hum:RemoveAccessories()
		end)
	end
end)

I'm working on a game with pre-set characters. My goal is to get the players' hats to be removed from the player to be replaced with preset ones. This script is not working and I'm not sure why can someone please help me? Thank you for taking the time out of your day to read this.

1 comment

0

Use a humanoid description.

1 answer

I have no clue why you are doing this in inside a remote event. The code itself is a bit hazardous due to the WaitForChild and that the variable char is outside the function scope.

I would simplify this code a lot by just using conventional event e.g. PlayerAdded, CharacterAdded.

Example

game:GetService('Players').PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(charModel)
		local hum = charModel:WaitForChild('Humanoid')

		hum.Died:Connect(function()
			hum:RemoveAccessories()
		end)
	end)
end)

The code above will remove all accessories not just hats. So you will need additional code to find all Accessories and check if they include a child named HatAttachment.

The Roblox accessories system will link attachments with the same name as to the attachment in the characters model.

Example

game:GetService('Players').PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(charModel)
		local hum = charModel:WaitForChild('Humanoid')

		hum.Died:Connect(function()
			
			-- loop through all children
			for i, v in pairs(hum.Parent:GetChildren()) do
				if v:IsA('Accessory') then 
					-- find accessory and handle
					local handle = v:FindFirstChild('Handle')
					-- remove only hats
					if handle and handle:FindFirstChild('HatAttachment') then
						v:Destroy()
					end
				end
			end
		end)
		
	end)
end)

I hope this helps. Please comment if you have any questions about this code.

2 comments

0

We are using a remote event because we are using an equipping system for the characters, we're firing the event to the server so the characters are changed for everyone in the server.

0

The equipping system should making the changes on the server side and not on the client side. I would review how this system works.

This discussion is preserved as it was. New answers, comments, and votes are closed.