Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Why does this event only listen once?

Asked by
Klamman 220 Moderation Voter
8 years ago

I'm having a lot of trouble with a script in my game:

game.Players.PlayerAdded:connect(function(player)
    wait(1)
    game.ReplicatedStorage.UpdateStatus:FireAllClients()
    player.Character.Humanoid.Died:connect(function()
        print("HUMANOID DIED")
        local playerNum
        for i, plr in pairs(players:GetPlayers()) do
            if plr == player.Name then
                playerNum = i
                print(player.Name .. "leaving game.")
            end
        end
        table.remove(playersPlaying, playerNum)
        print(player.Name .. "leaving game.")
    end)
end)

Can someone explain to me why the .Died event only seems to run once? To my knowledge, it should run like this: player joins, event's connected. Whenever the player dies from that point on, the code will run. Is this not the case? If so, can someone explain why? Help is much appreciated.

1 answer

Log in to vote
1
Answered by 8 years ago

I think it has to do with static variables.

Basically, the character can change. Once it dies, it re-spawns a new Character. This might be the reason this is happening.

How can I fix this?

Use a CharacterAdded event. Like so,

game.Players.PlayerAdded:connect(function(player)
    plr.CharacterAdded:connect(function(char)
        wait(1)--I would also maybe remove this
        game.ReplicatedStorage.UpdateStatus:FireAllClients()
        char.Humanoid.Died:connect(function()
            print("HUMANOID DIED")
            local playerNum
            for i, plr in pairs(players:GetPlayers()) do
                if plr == player.Name then
                    playerNum = i
                    print(player.Name .. "leaving game.")
                end
            end
            table.remove(playersPlaying, playerNum)
            print(player.Name .. "leaving game.")
        end)
    end)
end)
The Character Added Event Fires Everytime the player's character Respawns, providing a variable of the character.

I hope I helped.

Good Luck!

Ad

Answer this question