How can I get a reference to the main camera if it's in another scene and on dontdestryonload ?

The main camera is inside Player and I want to reference access the camera from the script on the object

Window Interaction Scene

The script is :

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class Window_Interaction_Action : MonoBehaviour
{
    private Camera playerCamera;
    private List<GameObject> birds = new List<GameObject>();

    private void Awake()
    {
        playerCamera = GameObject.Find("MainCamera").GetComponent<Camera>();
    }

    public void RandomBirdCamera()
    {
        birds = GameObject.FindGameObjectsWithTag("Flocking Bird").ToList();
        GameObject randomBird = birds[Random.Range(0, birds.Count)];

        List<Transform> randomBirdChilds = randomBird.GetComponentsInChildren<Transform>().ToList();
        foreach (Transform child in randomBirdChilds)
        {
            if (child.name == "head")
            {
                child.gameObject.AddComponent<Camera>();
                playerCamera.enabled = false;
            }
        }
    }
}

This screenshot is before running the game in editor mode :

Now I’m using Find before I just used a public Camera playerCamera;
The problem is when I’m running the game the Player will be on the scene : DontDestroyOnLoad and the object with the script will stay in the scene Game so it will give me error that the camera is missing :

This screenshot is after running the game :

Seems like GameObject.Find is not working between scenes.

1 Like

I’m not entirely sure that I understand the issue. There is only one active scene. The camera is in the currently active scene if you have dontDestroyOnLoad active. The camera being absent can only ever happen if you run the follow-up scene (the one without the camera) directly, without running the initial one.

If the camera was correctly brought over, simply using

Camera myCamera = Camera.main;

will return the active camera. Luckily, there is no need for elaborate Find and GetComponent required :slight_smile:

Be sure to use Camera.main only sparingly, as it internally executes a Find(). Accessing an object in a scene that isn’t loaded is not possible.

4 Likes

And by “sparingly” I think @csofranz means “get it once and keep the reference around,” rather than banging on it every frame.

2 Likes

Calling it once in the Awake did the trick.

playerCamera = Camera.main;
1 Like