Unity 101 – Smart Behaviours

The SmartBehaviour

The SmartBehaviour wraps all the performance tweaks I need into a single class for all your MonoBehaviours to inherit from instead of MonoBeahviour.

Why Smart Behaviours?

The reason it’s called SmartBehaviour is simply because I was thinking at the time ‘this is dumb’ when I had to rewrite all the boilerplate code for every single behaviour, no exceptions.

There is a lot of best practise in Unity, and often people will look at your code and go “why are you doing it that way, it’s bad, do it this way”.  This is what I call “best practise through best practise”.

It is much better if the tools themselves, frameworks, and convention, are used to enforce best practise.  This way, you know that by leveraging the right framework, you can avoid bad practise.

Why would I want to have Transform accessors and because my object doesn’t need to use the Transform?

Because there is no downside, and when do you do want it, it’s there in a consistent form, with no code required.

The Code

The code is available on my UnityCore repo along with the other Unity 101 content.  There are also prebuilt packages to pull in all the Unity 101 content to your projects quickly and easily.

In short, it simply provides accessors for things like “transform” which at runtime are poor performing, and stores them locally, an makes them accessible through _Transform, _Renderer etc.

public class SmartBehaviour : MonoBehaviour {
    private Transform _transform;
    public Transform _Transform {
        get {
            if(_transform == null)
                _transform = this.transform;
            return _transform;

As you can see from the code above, it is pretty simple, clean, and consistent.  So use it or write your own.  Please don’t rewrite it every time.

Unity 101’s is a series of posts about things I use and find fundamentally helpful in Unity.  They may not be the absolute best practise, but they are my practise.  
— Vaughan


Posted in:

One response to “Unity 101 – Smart Behaviours”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s