Search Unity

  1. Looking for a job or to hire someone for a project? Check out the re-opened job forums.
    Dismiss Notice
  2. Unity 2020 LTS & Unity 2021.1 have been released.
    Dismiss Notice
  3. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

How to write code for scene change in editor?

Discussion in 'Scripting' started by astracat111, Apr 10, 2017.

  1. astracat111

    astracat111

    Joined:
    Sep 21, 2016
    Posts:
    629
    So I've figured out previously how to write code for when a scene saves in the editor, but I can't figure out how to do it for when a scene loads.

    From what I understand from the coding api you can add a delegate to EditorSceneManager.activeSceneChanged. The problem is, I'm not exactly sure where to put the code.

    I have this:

    Code (CSharp):
    1.  
    2. //First:
    3. using UnityEditor.SceneManagement;
    4.  
    Then this in a method in a class:

    Code (CSharp):
    1. EditorSceneManager.activeSceneChanged += HelloWorld;
    Then this as the method I want to add to the delegate:

    Code (CSharp):
    1.  
    2. void HelloWorld() {
    3.     Debug.Log("Hello world.");
    4. }
    My thought is that it would be put inside of an editor script?
     
  2. astracat111

    astracat111

    Joined:
    Sep 21, 2016
    Posts:
    629
    Nvm, sorry I think I've found a simple solution with this:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. [ExecuteInEditMode]
    5. public class SceneScript : MonoBehaviour {
    6.  
    7.     bool HasRunOnce = false;
    8.  
    9.     void Update () {
    10.         if (HasRunOnce == false) {
    11.             Debug.Log ("One this once.");
    12.             HasRunOnce = true;
    13.         }
    14.     }
    15. }
    And then just attach that to a scene game object (or another game object) within the scene. Something I don't mind doing since I'm using templates for my scenes.
     
    Last edited: Apr 10, 2017
  3. tonemcbride

    tonemcbride

    Joined:
    Sep 7, 2010
    Posts:
    992
    You were correct with your delegate but they take parameters so you also need your own function to take those parameters too:

    Code (CSharp):
    1. UnityAction<Scene, Scene> activeSceneChanged;
    2. UnityAction<Scene, LoadSceneMode> sceneLoaded;
    3. UnityAction<Scene> sceneUnloaded;
    e.g.
    Code (CSharp):
    1.  
    2. void MyClassActiveSceneChanged( Scene arg0 , Scene arg1 )
    3. {
    4.    Debug.Log("Active Scene Changed");
    5. }
    6.  
    The documentation doesn't actually tell you the parameters which is pretty annoying.
     
    astracat111 likes this.
unityunity