Subscribing to an event in ExecuteAlways

The requirement is to have a cascading effect on components in the inspector.
public class ObservableClass : Monobehavior
{
public delegate void InitializeHandler();
public event InitializeHandler Initialized;

void Initialize()
{
// initialize code here
if (Initialized != null)
Initialized.Invoke();
}
}

// This is a sibling component that needs to do something after the object has been initialized by the ObservableClass object.
[ExecuteAlways]
public class SubscriberClass : MonoBehavior
{
ObservableClass Observable;

public void MyMethod()
{
// do something to the object…
}
void onEnable

{
gameObject.GetComponent().Initialized += MyMethod;
}
/…Now, when I call this, nothing happens because this behavior is enabled and disabled in its own execution, so it is never in a subscription state when the event is being fired./

//private void onDisable()
//{
// gameObject.GetComponent().Initialized -= MyMethod;
//}
}

Question: Initialized is -always Null because it didn’t exist (in edit mode)?

Does it get destroyed every time?

Without even trying to read the unformatted code above, when you press PLAY / STOP, Unity tears down everything in the scene, recreates it and injects what it can from serialization. This would not normally contain things you subscribe in code, but stuff you drag in in the inspector.

If you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: Using code tags properly

1 Like