So as I was working on a project that has a bunch of UI panels I kept forgetting to disable certain panels before running the game or before committing it and my client would see the panels with the loading screen. Sure I could add a line to the controllers I have set up to set the default state, but there’s a bunch of controllers, not all of them have the panel assigned to them at start, not all of them are disabled (some are alpha 0, some are scale 0), and it’s really best when an object maintains its own default state. So I said to myself, “I really need a universal script to do this. Wouldn’t it be great to have some sort of drag-drop interface to do this?” I didn’t really want to write a custom inspector for it since that would take 2 scripts. Then it occurred to me: BUTTONS they have on-click events. That’s what I want. And boy was it easy!
So all you have to do is create a MonoBehaviour derived class. Declare using UnityEngine.Events, declare a public UnityAction variable. Then in your Start() method just Invoke() that event. Super simple. Here’s the code:
Way too easy. Of course, you could extend this to also do Awake, OnEnable, OnLevelWasLoaded, OnApplicationPause, OnBecameVisible/Invisible, OnApplicationQuit, and OnDisable (I’d highly recommend avoiding using any of the main loop events). A very neat and clean way to do a simple delegate that’s assignable from the inspector and can set the value on pretty much any component.
I hope you all find this as handy as I have. Feel free to post a more extended version here if you like sharing with others.
As always, thanks for reading!
On a personal note, my wife just published her first book! If you like kick-ass female protagonists, spies, and a bit of sci-fi then please check out her book on Amazon.