Error GetActiveScene and MonoBehaviour

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.

    using UnityEngine;
    using UnityEngine.SceneManagement;

    public class SceneChange : MonoBehaviour  {

        private int sceneNumber = SceneManager.GetActiveScene().buildIndex;

        private void OnTriggerEnter(Collider other) {
            switch (sceneNumber) {
                case 0: // Title Screen
                    SceneManager.LoadScene(sceneNumber + 1);
                    break;
                case 1: // Tutorial or OpenForTakeOff
                    SceneManager.LoadScene(sceneNumber + 1);
                    break;
                case 2: // Space
                    SceneManager.LoadScene(sceneNumber + 1);
                    break;
                case 3: // Blue Planet
                    SceneManager.LoadScene(sceneNumber + 1);
                    break;
                case 4: // Star Level
                    SceneManager.LoadScene(sceneNumber + 1);
                    break;
                case 5: // GameOver
                    SceneManager.LoadScene(0);
                    break;
            }
        }
    }

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?

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.

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.

int sceneNumber { get { return SceneManager.GetActiveScene().buildIndex; }}
1 Like