2
votes

I am trying to make a game in Roblox that spawns every player onto a map and they have to try kill each other. However my problem is when the last player is left I don't know how to spawn him back in my lobby. I have all the players in the game stored in an array, once a person dies they are removed from the array. I have tried setting the last players health to 0 but whatever way the player is stored in the array it won't work with getting their humanoid.

This is my code so far:

if #plrs == 1 then
    plrs[1].Character.Humanoid.Health = 0
end

I am making my plrs array like this:

local plrs = {}

for i, player in pairs(game.Players:GetPlayers()) do
    if player then
        table.insert(plrs,player) --Add each player to the Player array
    end
end

Thank you for any help.

3
Can you include how you make your plrs array?Nifim
I updated it to show how I make the array, thanks.Crann Moroney

3 Answers

2
votes

I would recommend using player:LoadCharacter() to force spawn a new player character. This method has the advantage of not showing a death screen, instead it destroys the old character and spawns a new one straight after.

You should note that this method will also clear their backpack and playerGui just incase any of that is important to your game.


As a side note, there is no need to use a for loop to get the players as the function game.Players:GetPlayers() returns an array as it is already. Unless you are doing additional checks to the players in that loop all you need is this:

local plrs = game.Players:GetPlayers()
0
votes

Thank you everybody who tried to help.

I figured out my own problem after a lot of research and reading back through my code.

if #plrs == 1 then
    player.Character.Humanoid.Health = 0
end
-3
votes

You have a standard indexing error here. In code, you always start counting at 0, and you are actually asking for the (plrs[1]) second item in your array. Simply change your code to this:

if #plrs == 1 then
    plrs[0].Character.Humanoid.Health = 0
end