- Home /
Run script in Edit mode when paused?
Is there a way to have a script run when you have paused the game in the Editor and you are manipulating the scene in the Scene View?
There is the ExecuteInEditMode attribute, which is great, but it only runs in Edit mode or Play mode. It stops running when you hit the Pause button. I need one of my scripts to be running even when the game is paused and you are flying around the scene in Edit mode.
Answer by GhostTownGames · Oct 24, 2017 at 10:02 AM
I ran across this too and think I've found a cleaner work around using the EditorApplication class:
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
[ExecuteInEditMode]
public class ExampleClass: MonoBehaviour
{
#if UNITY_EDITOR
void Awake()
{
EditorApplication.update += EditorUpdate;
}
void EditorUpdate()
{
if( (!EditorApplication.isPlaying) || EditorApplication.isPaused )
{
//Do something
}
}
void OnDestroy()
{
EditorApplication.update -= EditorUpdate;
}
#endif
}
(You may not need the if statement to check the game isn't running and unpaused in your case.)
Answer by colinf · Feb 15, 2011 at 11:24 PM
Edit: Crap. This works fine as long as you don't have the Scene and Game views open at the same time. As soon as you can see both of them, though, there is a good chance that OnDrawGizmos() is going to be called during play mode.
-
It's such a glaring problem that I have to assume that it's by design; maybe there's some distinction between editing and editing-while-paused that isn't obvious to me.
My workaround: Avoid the ExecuteInEditMode() attribute and Use OnDrawGizmos() to handle running the script in the editing modes.
// called only during play mode function Update() { RunTheScript(); }
// called in both normal and paused editing modes but not during play function OnDrawGizmos() { RunTheScript(); }
The problem with this solution is that it offers no way to execute something in a LateUpdate() equivalent. So if some other objects refer to the results of calculations done by RunTheScript() it's a crapshoot whether they'll get them this frame or the next.
Answer by GlitchEnzo2 · Apr 06, 2011 at 07:04 AM
What I ended up doing was writing a custom editor that operates on GameObject objects. In the OnSceneGUI() method, I put my code that I want run (which in my particular case, sets camera matrices in a shader). This works fairly well except that you MUST have an object selected in the hierarchy in order for the script to run.
using UnityEngine; using UnityEditor;
[CustomEditor(typeof(GameObject))] public class UpdateCameraMatrices : Editor { void OnSceneGUI () { Camera camera = Camera.current; Shader.SetGlobalMatrix("viewMatrix", camera.worldToCameraMatrix); Shader.SetGlobalMatrix("projMatrix", camera.projectionMatrix); } }