Search Unity

Error GetActiveScene and MonoBehaviour

Discussion in 'Scripting' started by MatthewTCC, Oct 17, 2019.

  1. MatthewTCC

    MatthewTCC

    Joined:
    Oct 1, 2019
    Posts:
    3
    So I'm trying something new. I want to attach one script to a trigger object and do a scene change. There are multiple triggers per scene.

    Code (CSharp):
    1.     using UnityEngine;
    2.     using UnityEngine.SceneManagement;
    3.  
    4.     public class SceneChange : MonoBehaviour  {
    5.  
    6.         private int sceneNumber = SceneManager.GetActiveScene().buildIndex;
    7.  
    8.         private void OnTriggerEnter(Collider other) {
    9.             switch (sceneNumber) {
    10.                 case 0: // Title Screen
    11.                     SceneManager.LoadScene(sceneNumber + 1);
    12.                     break;
    13.                 case 1: // Tutorial or OpenForTakeOff
    14.                     SceneManager.LoadScene(sceneNumber + 1);
    15.                     break;
    16.                 case 2: // Space
    17.                     SceneManager.LoadScene(sceneNumber + 1);
    18.                     break;
    19.                 case 3: // Blue Planet
    20.                     SceneManager.LoadScene(sceneNumber + 1);
    21.                     break;
    22.                 case 4: // Star Level
    23.                     SceneManager.LoadScene(sceneNumber + 1);
    24.                     break;
    25.                 case 5: // GameOver
    26.                     SceneManager.LoadScene(0);
    27.                     break;
    28.             }
    29.         }
    30.     }
    The error I get is UnityException: GetActiveScene is not allowed to be called from a MonoBehaviour constructor, call it from Awake or Start instead.

    When I have done this in the past, I just throw SceneManager.LoadScene(2); into the OnTriggerEnter and it works, why not now?
     
  2. I don't know how it worked before.

    Put it into an Awake method. It's similar to what you have but you initialize your variable from Awake.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    That definitely works, but for a general purposes solution you can also make it a lazy getter, which means that the value in there won't get stale (in this case pretty sure the value of scene index is constant) between when the scene loads and when you use it, which might matter with other pieces of data.

    Code (csharp):
    1. int sceneNumber { get { return SceneManager.GetActiveScene().buildIndex; }}
     
    Joe-Censored likes this.