- Home /
How to call a function on all scripts which are derived from monobehaviour on awake and ondisable?
I need to call a certain function on all scripts which are inherited from monobehaviour on awake and ondisable. How to do that?
For example if i need to print the name of the gameobjects which has the monobehaviour script on awake and ondisable how to do that?
Answer by Baste · Sep 16, 2014 at 12:48 PM
I can't quite see why you'd want this, but if you insist, I can see two ways:
1: create a MyMonoBehaviour class that does what you want on Awake() and OnDisable(). Have every other script inherit from MyMonoBehaviour instead of MonoBehaviour.
The Awake and OnDisable methods needs to be protected virtual, as your other scripts has to override them (and call base.Awake and base.OnDisable) to be able to define their own behaviour for the methods
2: Make a crazy controller that on every frame:
picks up all gameObjects in the scene with FindObjectsOfType()
figures out which ones are new, add them to a list and call the Awake-stuff on them
if anything in the list was enabled last frame but is now disabled, call the OnDisable stuff on it
if anything in the list is destroyed, remove it from the list
The second method is harder, especially when it comes to keeping track of what status stuff had on the last frame. It will also eat more resources; every frame you add an O(n) operation, where n is the number of scripts in the game. So I'd recommend method 1. Or do what a sane person would do, and add debug messages where you need them instead of EVERYWHERE.
This has enough detail to justify being an answer.
Another way would be to write a custom wrapper for Instantiate that registers the newly created GameObject with a controller class. That's a cheaper method then checking every frame.
I just said that i want to print names of all objects for an example. That is not what i intend to do. What i am actually doing is i created an atrribute called save and it will retive the value from playerprefs of the values marked with that attribute on awake and save it on disable. I was just wondering if there is anyother way other than inheriance. Looks like i just don't want to complicate things any way thank you so much for your input.