Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

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

Discussion in 'Editor & General Support' started by firestar9114_unity, Sep 24, 2018.

  1. firestar9114_unity

    firestar9114_unity

    Joined:
    Mar 2, 2018
    Posts:
    11
    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:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class SceneActivator : MonoBehaviour {
    7.  
    8.     void Awake()
    9.     {
    10.         SceneManager.SetActiveScene(SceneManager.getCalledFrom());
    11.     }
    12. }
    13.  
    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:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class SceneActivator : MonoBehaviour {
    7.  
    8.     void Awake()
    9.     {
    10.         SceneManager.SetActiveScene(SceneManager.getSceneContainingGameObject(gameObject));
    11.     }
    12. }
    13.  
    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...
     
  2. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,292
    You can find out to which scene object relates by using gameObject.scene. It is "default" for prefabs.

    Alternatively, check against scene.IsValid.
     
    Last edited: Jan 8, 2023
    unity_3Vgvc20-AT9hew likes this.
  3. firestar9114_unity

    firestar9114_unity

    Joined:
    Mar 2, 2018
    Posts:
    11
    Thank you, this sounds like exactly what I was looking for! :)
     
    Last edited: Sep 24, 2018