Unity Lists and assigning GameObject to list in runtime!

Hello i need help. I need to assign my both players (P1, P2) to an array. But then i did a quick google search i found out that using a List is a better option. Here is my script, i got no errors but it does not find P1 or P2 but their names are “P1” and “P2” Can someone help me? thanks

using System.Collections;
using UnityEngine.AI;
using System.Collections.Generic;
using UnityEngine;

public class SetDestinaiton : MonoBehaviour {

	public List<Transform> players = new List<Transform> ();
	Transform dest;

	void Start ()
	{
		players.Add (GameObject.Find ("P1").transform);
		players.Add (GameObject.Find ("P2").transform);
		dest = players [Random.Range (0, players.Count)];
	}

	void Update ()
	{
		GetComponent<NavMeshAgent> ().destination = dest.transform.position;
	}
}

If the number of players stays the same for the whole game, an array would be the better option. Looking at your code, that seems to be the case.

I’m not sure why GameObject.Find isn’t working but an easy way to avoid using it would be to declare a public array and just set that array to size 2 in the editor and pass the players to it directly.

using System.Collections;
 using UnityEngine.AI;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class SetDestinaiton : MonoBehaviour {
 
     public Transform[] players;
     Transform dest;
 
     void Start ()
     {
         dest = players [Random.Range (0, players.Length)];
     }
 
     void Update ()
     {
         GetComponent<NavMeshAgent> ().destination = dest.transform.position;
     }
 }