Hi, I’m having issues making it so when a player dies it takes away one live displayed on a gui. It works, but it only works the second time and beyond that. Is there a way I can fix this?
Here is the code:
local lives = 3
game.Players.PlayerAdded:Connect(function(plr)
local ui = plr:WaitForChild("PlayerGui"):WaitForChild("Lives")
plr.CharacterAdded:Connect(function(char)
local hum = char:WaitForChild("Humanoid")
hum.Died:Connect(function()
for i, uielement in pairs(ui:GetChildren()) do
if uielement.Name == tostring(lives) then
uielement:Destroy()
lives = lives - 1
end
end
if lives == 0 then
wait(3)
game.ReplicatedStorage.ReachedZero:FireClient(plr, plr.Name)
end
end)
end)
end)
It could be because you have no UI element named 3.
You should also include your variable inside the .PlayerAdded, and I’m not sure why you’re firing the player’s name to the client, since they can retrieve it locally. Your current method would increase network usage, which isn’t good.
Code:
game.Players.PlayerAdded:Connect(function(plr)
local ui = plr:WaitForChild("PlayerGui"):WaitForChild("Lives")
local lives = 3
plr.CharacterAdded:Connect(function(char)
local hum = char:WaitForChild("Humanoid")
hum.Died:Connect(function()
local uiElement = ui:FindFirstChild(lives)
if uiElement then
uiElement:Destroy()
lives -= 1
end
if lives == 0 then
task.wait(3)
game.ReplicatedStorage.ReachedZero:FireClient(plr, plr.Name)
end
end)
end)
end)
local Player = game:GetService("Players").LocalPlayer
local Gui = (...)
local Humanoid = (...)
local Lives = 3
Humanoid.Died:Connect(function ()
Lives -= 1
end)
You’re destroying the wrong UI element on the first player death because you’re checking for the UI element with the current lives value and then decreasing lives afterward. To resolve this, just decrement lives before destroying the UI element.
local lives = 3
game.Players.PlayerAdded:Connect(function(plr)
local ui = plr:WaitForChild("PlayerGui"):WaitForChild("Lives")
plr.CharacterAdded:Connect(function(char)
local hum = char:WaitForChild("Humanoid")
hum.Died:Connect(function()
lives = lives - 1
for _, uielement in pairs(ui:GetChildren()) do
if uielement.Name == tostring(lives) then
uielement:Destroy()
end
end
if lives == 0 then
wait(3)
game.ReplicatedStorage.ReachedZero:FireClient(plr, plr.Name)
end
end)
end)
end)