- Home /
[ExecuteInEditMode] OnEnable Running twice on Play?
Hi. I have a GameObject with a simple script in C#, which has [ExecuteInEditMode] , however, when OnEnable runs, I want to be able to diferentiate if I'm in Play mode, or in the Editor. For which I am using Application.IsPlaying . However, when I click on Play, the OnEnable triggers twice, one with Application.IsPlaying being set to true, and another with it being set to false, this leads to some weird behavior. Is this expected? I don't remember having this problem previously. What would be the architecture guidelines to have one single call on each, at the appropriate times (Editor OnEnable, Play OnEnable).
Here is the script:
#if UNITY_EDITOR
using UnityEditor;
#endif
[ExecuteInEditMode]
public class TestScript : MonoBehaviour {
void OnEnable(){
Debug.Log("On Enable");
if (Application.isPlaying)
PlayOnEnable();
else
EditorOnEnable();
}
void PlayOnEnable(){
Debug.Log("Play On Enable.");
}
void EditorOnEnable(){
Debug.Log("Editor On Enable.");
}
}
When I enter Play mode in the editor, OnEnable is triggered twice, one for EditorOnEnable and another for PlayOnEnable, in this order.
Thank you in advance
Hi! Could you please file a bug report and post the case number here? I'm going to soon be fixing something else related to ExecuteInEdit$$anonymous$$ode
, so I'd like to look at this at the same time.
Answer by quizcanners · Jul 31, 2017 at 04:57 PM
I had a similar issue:
[ExecuteInEditMode]
public class TestScript : MonoBehaviour {
public int version = 0;
private void OnDisable()
{
Debug.Log("Disabling Playing: "+Application.isPlaying+" version "+version);
version++;
}
private void OnEnable()
{
Debug.Log("Enabling Playing: " + Application.isPlaying + " version " + version);
version++;
}
}
The Output:
Enabling Playing: False version 0
>> I click Play.
Disabling Playing: False version 1
Enabling Playing: False version 2
Disabling Playing: False version 3
Enabling Playing: True version 1
The solution to the problem I had was to use "EditorApplication.isPlayingOrWillChangePlaymode", it will return TRUE for those 4 calls after "I clicked Play" and FALSE for everything else.
Playing == True && EditorApplication.isPlayingOrWillChangePlaymode == True
to find the OnEnable I need.
I see little point in describing my problem, since it was a direct consequence of not knowing about additional pair of Enable/Disable calls. Can anyone explain where those 2 calls are coming from and what are they for?
I'm facing some similar issue. Had a breakpoint inside an OnEnable function and got in an infinite loop of OnEnable calls while debugging. It seems like switching from editor to Visual Studio and back to editor makes the call to OnEnable function (similar to when it compiles the source code upon switching to Unity editor from the code editor). Not sure why that's happening, tho.