Hat boost is given to everybody in the server with hat

I am making a Plants VS Zombies themed item in my game where you can equip a hat which gives 50 extra maxhealth which works but whenever another person equips that item too, it gives another extra 50 to both people making them have both 200 health instead of 150, it keeps stacking for every player that equips it.

local Defense = 50
local AddHealth = 50
local boostsApplied = {}
local function ApplyBoost(character)
	local humanoid = character:FindFirstChildOfClass("Humanoid")
	if humanoid and not boostsApplied[character] then
		humanoid.MaxHealth = humanoid.MaxHealth + Defense
		humanoid.Health = humanoid.Health + AddHealth
		boostsApplied[character] = true
	end
end
local function RemoveBoost(character)
	local humanoid = character:FindFirstChildOfClass("Humanoid")
	if humanoid and boostsApplied[character] then
		humanoid.MaxHealth = humanoid.MaxHealth - Defense
		humanoid.Health = math.max(humanoid.Health - AddHealth, 0)
		boostsApplied[character] = nil
	end
end
local function CheckHatEquipped(character)
	for _, accessory in ipairs(character:GetChildren()) do
		if accessory:IsA("Accessory") and accessory.Name == script.Parent.Name then
			return true
		end
	end
	return false
end
local function OnCharacterAdded(character)
	local player = game.Players:GetPlayerFromCharacter(character)
	if player then
		local heartbeatConnection

		heartbeatConnection = game:GetService("RunService").Heartbeat:Connect(function()
			if character.Parent then
				if CheckHatEquipped(character) then
					if not boostsApplied[character] then
						ApplyBoost(character)
					end
				else
					if boostsApplied[character] then
						RemoveBoost(character)
					end
				end
			else
				heartbeatConnection:Disconnect()
				RemoveBoost(character)
			end
		end)
		character.AncestryChanged:Connect(function(_, parent)
			if not parent then
				heartbeatConnection:Disconnect()
				RemoveBoost(character)
			end
		end)
	end
end
game.Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(OnCharacterAdded)
end)
for _, player in ipairs(game.Players:GetPlayers()) do
	if player.Character then
		OnCharacterAdded(player.Character)
	end
end

1 Like

consider doing it per player on per character

1 Like

I dont really see an issue with this. Is this all the code?

Nevermind i fixed it. aaaaaaaaaaaaaaaa

Mark this as the solution if you found your answer

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.