- Home /
Good practice to do a base extend of MonoBehaviour?
I am wondering whether it is a good practice to do a (basically void) extension of MonoBehaviour and make all your classes extension of your base - so you can anytime inject custom "trapping" code. (Searched the community but found no answers.)
I personally think its a pretty good idea. It is also mentioned here http://devmag.org.za/2012/07/12/50-tips-for-working-with-unity-best-practices/ #21
Answer by Bunny83 · Nov 15, 2013 at 12:28 PM
The link PAEvenson posted above suggest an own base class to implement general purpose functions which every MonoBehaviour needs. If that's not what you want, having an empty base class doesn't give you any benefit.
You can't inject trapping code afterwards. This would only work if you had implemented all callbacks Unity provides in the base class as empty virtual methods and you always override them in your actual classes. This however would give you the worst possible preformance. Unity does optimisations depending on what methods you've implemented. If you always implement all methods Unity will call all of them.
If you think you have enough new things that every MonoBehaviour needs, feel free to make a base class, but keep in mind that pure functions can be implemented as extension methods. Only for per instance data fields you need a base class.
In most cases it doesn't make that much sense to create a base class. It's more appropriate for a group of classes that share a lot things. For example for a Node based system you might create a Node base class and derive other Node types from Node. However in Unity it's usually better to use the component system. Take a look at the GameObject. Every gameobject has a Transform component. This component builds the actual tree hierarchy. The actual GameObjects are just data-containers with no relation to each other. Only the Transform component has the parent link but this also doesn't link to other GameObjects but other Transforms.
Components should be designed for a certain task. To get the final object you attach all components an object needs to get the desired behaviour. It's a bit more difficult to write general purpose components, but in the long run it's way more flexible.
Thanks for the exhaustive and clear answer, really helped.
Your answer
![](https://koobas.hobune.stream/wayback/20220613121945im_/https://answers.unity.com/themes/thub/images/avi.jpg)