How to subscribe method to OnDisable in a gameObject.

Hi, I’ve just started using events and delegates, I know how to subscribe to some events in UI buttons/elements. But how do you subscribe or un-subscribe a method to the OnEnable/OnDisable events in a GameObejct? (if that’s possible?).

I’m basically making a little prompt system with different possible types of prompts (which is using functionality from a third party asset-not explicitly made for that).

Anyway, I need to do add the method from an external script because I’m not always going to be doing this to the same menu and I’m not always going to be passing the same method. Also, at times the menus are going to be shared - one object will have to wait until the menu is free to be used (a limitation in the third party asset… the asset doesn’t have a method to instantiate it’s own menus, because the core asset doesn’t need it…).

Sadly, I’m still too green to replicate the features provided by the asset, and if possible I’d like to not have to attach anything extra to the menus to make setup always easy. Hence I want to use events… And I need to trigger some random method when one of the prompts closes (I’m currently using a coroutine with wait time to detect it)…

You can take a look in this link, can use delegates to subscribe and unsubscribe in OnEnable(), OnDisable() methods respectively.

Alternatively, if you want to have a custom delegate to cater for all sorts of event, you can create a custom class to hold the delegate

// class to hold the delegates
    namespace MyPackage
     public delegate void CustomAction(object[] param);

// class to run it
 public class TestClass : MonoBehaviour 
       public static CustomAction OnActionClicked;

 	void OnEnable()
               TestClass.OnActionClicked += HandleOnClick;
 	void OnDisable()
             TestClass.OnActionClicked -= HandleOnClick; 

For full source, you can take a look at my GitHub, i’ve written some code to it.

Hope it helps.