- Home /
Is there a way of subscribing to Update() without the script being attached to a GameObject?
I'm only just beginning to learn about events in C#, and I understand that Update() is an event. I want to create a class that I make lots of instances of, which update every frame. There seem to be only two ways of doing that: either instantiate them as prefabs, in which case my hierachy is filled with many gameobjects (which I, being a bit OCD don't like!) - or, call all of their Update() methods from a proper GameObject's Update() method.
But is it possible to derive my class from MonoBehaviour and somehow subscribe manually to the MonoBehaviour.Update() event, so that the instanced objects can update automatically every frame without the script being attached to a prefab?
Answer by Bunny83 · Sep 29, 2011 at 11:59 PM
No, the MonoBehaviour-base-class is derived from Component and therefore can only exist on GameObjects. You can't create Components via "new".
In editor-scripts there's the update-delegate you can use, but unfortunately there is nothing similar for the runtime.
You still can derive your class from MonoBehaviour and even attach them to the same GameObject multiple times or just parent the GameObjects to an empty "folder"-GameObject so your hierarchy stays clean. Seperate components are easier to debug since you can simply make things public and view them in the inspector or add a temporary OnGUI to it.
However, i'm a friend of the custom-event-approach. I did a lot with custom interfaces or delegates. That's also the reason why i hate SendMassage :D. Well it could be quite useful in some cases but i simply don't like it. (string-based function calls are a no-go in my eyes... like the string-based GetComponent function they can't be checked by the compiler)
Thanks - I suspected as much. Ah, but maybe as you suggest I can make a custom event that goes in a GameObject's Update() and so gets fired each frame, and then make each new instance of the custom class subscribe to that? In that way I could create any number of different custom classes that subscribe to my CustomUpdate (or perhaps EveryFrame - I love choosing names!) event, and I don't have to keep writing code blocks to manually update each instance? Am I understanding that correctly?
I figured out a great solution using the above method - thanks for the inspiration! I was really pleased with myself. Of course, then I went to add it to the Unify wiki and found an almost identical script with better functionality than $$anonymous$$e!