- Home /
Is there any way to call OnLevelLoaded when loading a scene in editor?
Hey, I need to run some code when I open a scene in the editor. Is there anything similar to OnLevelLoaded that gets called when I do that? Or any workouround to do this would also be appreciated. Thanks.
Answer by Jamora · Jul 26, 2013 at 01:36 PM
I couldn't find a callback for scene changes, so I used the OnHierarchyChange callback instead, a that (should) change when a new scene is loaded.
Now, It loads itself on Editor startup, and also creates a menuitem for turning it off/on. It is sort of hard to tell when it's running, so you might want to make a marker of some sort so you know when it's on.
 using UnityEngine;
 using UnityEditor;
 
 [InitializeOnLoad]
 public static class SceneChangeDetector 
 {
     static string loadedLevel;
     static bool working = false;
     
     static SceneChangeDetector(){
         Constructor();
     }
     
     [MenuItem("Detectors/SceneDetector")]    
     static void Constructor(){
         loadedLevel = EditorApplication.currentScene;
         if(!working){
             EditorApplication.hierarchyWindowChanged += OnHierarchyChange;
             Debug.Log("Turning Scene Detector on...");
             working = true;
         }else{
             Debug.Log("Turning Scene Detector off...");
             working = false;
             EditorApplication.hierarchyWindowChanged -= OnHierarchyChange;
         }
     }
     
     static void OnHierarchyChange(){
         if(EditorApplication.currentScene != loadedLevel){
             loadedLevel = EditorApplication.currentScene;
             /*Scene has changed; implementation here*/
         }
     }
 }
Answer by TonyLi · Jul 26, 2013 at 01:20 PM
Try adding ExecuteInEditMode to the script that contains OnLevelWasLoaded().
I couldn't get that to work. I think OnLevelWasLoaded is called from Appliaction.LoadLevel. At least Application.loadedLevel etc. only change when that is called.
Your answer
 
 
             Follow this Question
Related Questions
Adding functions in editor 1 Answer
How to Load/Unload assets in Editor? 0 Answers
Unity editor inspector delegate / function pointer? 2 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                