When entering playmode, OnEnable will be called twice for MonoBehaviours with the [ExecuteAlways] attribute. Aside from performance problems of double initialization, the first OnEnable also does not follow the execution order of the script.
In my case, I have a UI Toolkit UIDocument, where I want to add VisualElements to the rootVisualElement.
In EditMode, this works just fine because OnEnable is called after the UIDocument.
In PlayMode, this throws errors because OnEnable is called twice. Once some time before the UI Document and once when it should be called.
Expected behavior is that a script with execution order of -50 should execute after a script with execution order of -100.
[DefaultExecutionOrder(-50)]
public class ExampleCanvas : MonoBehaviour
{
//Assigned in the inspector
public UIDocument document;//Execution order of -100
private void OnEnable()
{
Debug.Log("Enable");//This will log "Enable" twice
document.rootVisualElement.Add(new VisualElement());
//First OnEnable:
//[Error] UIDocument has yet to be initialized, so rootVisualElement is still null
//Second OnEnable:
//[No Error] UIDocument has been initialized, so rootVisualElement is no longer null
}
}