Cannot assign the Player to the Camera automatically

Goodday!

I am trying to modify MainCamera’s script, so it finds the Player and assign it to itself.
By default you just drag-drop the Player’s gameObject into a MainCamera reference slot via Inspector, but I want camera to find the right gameObject [by Tag] and assign it upon the new Scene load.

And this code I have there does not work… or any variations I already went through… Ouch. I am stuck.

Thought this could be the one, but no dice :confused:

Your method of finding object why FindGameObjectWithTag is not ever used due to massive performance issue. but I will tell you that find game objects will return game objects not the CameraTarget script.

Use

Gameobject[] playerArray = GameObject.FindgameObjectsWithTag("Player");
for( int i=0; i<playerArray.Length,i++)
{
    if( playerArray.GetComponent<CameraTarget>() )
        _CameraTargets.Add( playerArray.GetComponent<CameraTarget>() );
}

Using FindWithTag is okay is used in Awake or Start. Just best to avoid in Update, methods called multiples times per frame or often. FindWithTag will return a GameObject type but your list is a CameraTarget type. You have to check if the player game object returned has a CameraTarget component/script on it

public void Start()
{
    // Find and return the player GameObject
    GameObject   player = GameObject.FindWithTag("Player");
      
    // Assign a reference to the CameraTarget component on the player GameObject
    // If a CameraTarget component does not exist on the player, this will be null
    CameraTarget target = player.GetComponent<CameraTarget>();
      
    // Check if the target has a value (not null)
    // If so, add target to the CameraTarget list
    if (target) CameraTargets.Add(target);
}