- Home /
OnDisable/OnDestroy Execution Order
I have a number of objects, A through F for this example, and I am seeing some behavior that is confusing to me when exiting a level or stopping play mode. The OnDisable/OnDestroy execution order is as presented:
A OnDisable
B OnDisable
C OnDisable
A OnDestroy
B OnDestroy
C OnDestroy
D OnDisable
E OnDisable
F OnDisable
D OnDestroy
E OnDestroy
F OnDestroy
Please find attached an example via the Unity console.
This presents a problem because I am referencing other components in OnDisable; however, they are sometimes already destroyed (I could check to see if the reference is already destroyed and then not touch it, but that is an ugly solution for a problem which should not exist). The script execution order for all of these components is the same.
Is there a proper workaround for this behavior?
Thanks.
how will you know if they are destroyed if you don't check? you can have a List with the items in and remove them when they are destroyed then you only check the ones that are left. but at some point you will need to check whats happening.
I should have been more explicit in the question, but the "destroyed" reference exists for the duration of the entire level, but the components which access it do not exist for the entire level duration. So to the component's point of view, the reference is never destroyed.
Similar to how Awake() is used for setting up internal state and OnEnable() is used for dealing with dependencies between components, OnDisable() could be used for dealing with dependencies and OnDestroy() could be used for cleaning up internal state.
So to answer your question, the referenced object should never be destroyed at the time of access. However, with the current OnDisable/OnDestroy behavior at level end / player stop, the reference sometimes is.
Answer by Elvis083 · Mar 03, 2015 at 12:17 PM
You can write simple script for disable all scripts in OnApplicationQuit event. It will solve your problem with errors when exit play mode.
using UnityEngine;
using System.Collections;
public class Deactivator : MonoBehaviour {
void OnApplicationQuit() {
MonoBehaviour[] scripts = Object.FindObjectsOfType<MonoBehaviour>();
foreach (MonoBehaviour script in scripts) {
script.enabled = false;
}
}
}
Answer by alenwesker · Apr 25, 2014 at 08:38 AM
I encounter the same problem. Not a nice solution, but just check every external variables, find out if they are null.
if(a != null) xxx;
if(b != null) xxx;
Something like what I do in C. Inelegant, but works.