2
\$\begingroup\$

Using the new Unity PlayerInputManager, I'm trying to create a page in the pause menu of the game where players can remove other players from the game. It's a split-screen game, and it seems to handle kicking the last player (i.e. if there were three players, kicking the third) just fine.

However, if we have three players and we destroy the gameobject for player two, it seems like the player index and the screen index of player three do not automatically adjust, and the screen remains split three ways. Here's some of the code I've tried:

public void KickPlayer(int i)
    {

      PlayerInput.Destroy(players[i]);
      players[i] = null;
      for (int j = i; j < 4; j++)
      {
          if (j+1 == 4 || players[j+1] == null)
          {
              players[j] = null;
          } else
          {
              players[j] = players[j + 1];
              players[j + 1] = null;
              PlayerInput pi = players[j].GetComponent<PlayerInput>();
              PlayerInput.Instantiate(players[j], j, pi.currentControlScheme, pi.splitScreenIndex-1, pi.devices.ToArray());
              PlayerInput.Destroy(players[j + 1]);
          }
      }
}

Although this code looks like it should rearrange and re-assign the split-screen, what I end up with when I spawn in three players and try to kick player two is player 0 with split-screen index 0, then there suddenly are three other players, player 1, 2, and a second copy of player 2 all sharing split-screen index 2.

What would be the best way to go about this? Is there a way to reassign player index and split-screen index?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

In your code, you first rearrange your collection, so that at the index j+1 a null is stored. Then you create a new instance of whatever is stored at index j. That might be your new copy of player 2. You should not need to do that at all.

It looks like you are storing players in array. I would consider using List. You can then shorten this all to:

public void KickPlayer(int i)
{
    GameObject.Destroy(players[i]);
    players.RemoveAt(i);
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .