Search Unity

Why is my Main Camera not loading when using "DontDestroyOnLoad?"

Discussion in 'Cinemachine' started by jleven22, Aug 6, 2019.

  1. jleven22

    jleven22

    Joined:
    Mar 26, 2019
    Posts:
    71
    I have a Main Camera and a Virtual Cam. They've been working fine up until this point, as I've just added new scenes. I've added the following to my main camera so as to retain (DontDestroyOnLoad) the camera between scenes:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CameraController : MonoBehaviour
    6. {
    7.  
    8.     private static bool retainCamera;
    9.  
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.         DontDestroyOnLoad(transform.gameObject);
    14.  
    15.         //Retain on Load of New Scene
    16.         if (!retainCamera)
    17.         {
    18.             retainCamera = true;
    19.             DontDestroyOnLoad(transform.gameObject);
    20.             Debug.Log("Camera Loaded");
    21.         }
    22.         else
    23.         {
    24.             Destroy(gameObject);
    25.         }
    26.     }
    27. }
    28.  
    However now when I start up the scenes, I get "Display 1 No Cameras Rendering." Also the Main Camera is gone from the hierarchy.

    What could be the reason the main camera isn't loading up at all?
     
  2. Gregoryl

    Gregoryl

    Unity Technologies

    Joined:
    Dec 22, 2016
    Posts:
    2,725
    Is it possible that start() is getting called on load, even for the DontDestroyOnLoad object? And consequently it's destroying itself?
     
  3. jleven22

    jleven22

    Joined:
    Mar 26, 2019
    Posts:
    71
    Haha it is exactly the case. Thanks!
     
    Gregoryl likes this.