List with every player on the Server

When someone leaves the server, the players array still wants to access his player gameobject. Is there a way to create the playerlist without the players array?

void Start() {
		playerlist = new List<Transform>();
		players = GameObject.FindGameObjectsWithTag("Player");
		foreach(GameObject p in players) {
			playerlist.Add(p.transform);
		}
	}
	
	void OnPlayerConnected() {
		playerlist.Clear();
		players = GameObject.FindGameObjectsWithTag("Player");
		foreach(GameObject p in players) {
			playerlist.Add(p.transform);
		}
	}
	
	void OnPlayerDisconnected(NetworkPlayer player) {
		playerlist.Clear();
		players = GameObject.FindGameObjectsWithTag("Player");
		foreach(GameObject p in players) {
			playerlist.Add(p.transform);
		}
	}

Shouldn’t OnPlayerDisconnected remove the player? All you’re doing is finding all the objects tagged “Player” and adding them to the list. You need to actually find the player object that represents the disconnected player and remove that object.

I do something like this, using the NetworkPlayer.guid property as part of the player object name so I can identify it easily…

void OnPlayerDisconnected(NetworkPlayer player)
{
    Transform playerTransform = GameObject.Find("Player_" + player.guid);
    if (playerTransform != null)
      Destroy(playerTransform.gameObject);        
  
    Network.RemoveRPCs(networkPlayer);
    Network.DestroyPlayerObjects(networkPlayer);
}

When adding the player you need to make sure you set the name to “Player_” + player.guid. I do this in OnPlayerConnected.

I also add all the player objects to a parent game object so the Find only has to search through a short list. This still isn’t the most efficient - using a Dictionary or somethign would be faster still. The basic idea though is that in OnPlayerDisconnect you need to be able to identify the specific player object that disconnected and remove it.