How to get the scene an instance of a script is running in?

I am using a multi-scene design with additive scene loading, and I would like to be able to easily set the active scene by having a monobehavior script in the primary scene of the set that does something like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneActivator : MonoBehaviour {
 
    void Awake()
    {
        SceneManager.SetActiveScene(SceneManager.getCalledFrom());
    }
}

obviously, the function “getCalledFrom()” is a fictional function, but is there something like it that can find the scene of the monobehaviour that called it? Looking through the scenemanager function it looks like the best I could do is have a string tagged with [serializefield] that can be set through the editor and fed into the call. I would like to avoid having to manually configure this if possible though. Alternatively maybe something like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneActivator : MonoBehaviour {
 
    void Awake()
    {
        SceneManager.SetActiveScene(SceneManager.getSceneContainingGameObject(gameObject));
    }
}

where “getSceneContainingGameObject()” returns the scene that holds the game object passed in or null if it is a prefab? I can’t find anything like this in unity though…

You can find out to which scene object relates by using gameObject.scene. It is “default” for prefabs.

Alternatively, check against scene.IsValid.

1 Like

Thank you, this sounds like exactly what I was looking for! :slight_smile: