1
\$\begingroup\$

I saw this pattern around and I was wondering what would be the pros and cons about it. Does this suffer performance issues ? If so what would be a better alternative?

using UnityEngine;
using System.Collections;

public class SomeClass : MonoBehaviour
{

    public static SomeClass instance;

    void Awake ()
    {
        instance = this;
    }

}

And in an other script use it like so:

SomeClass.instance.SomeMethod();
\$\endgroup\$
1
\$\begingroup\$

No, there is no performance issues with using static references. As it pertains to .net, you might even have better performance if you use static over instanced methods and fields (to such a little extent it is more a bit of trivia than something actually useful); I think the golden rule applies here: it is most important to make something that works and makes sense, and only after that should you worry about the optimization bit when and where it is needed. In some instances, having a static variable holding gameobjects/components makes perfect sense, and in those instances they are well suited.

\$\endgroup\$
1
\$\begingroup\$

Pros: You can access the same class from any script without connecting it.

Cons: There is a minimal overhead and if you have many scripts accessing the same singleton it can be messy to debug.

If you you use that pattern I would highly recommend making it more stable to prevent you from making mistakes in the future. There are however no run-time performance problems if you don't call this very often. If you implemented it as you diescribed in your post it would be slightly faster but that is of academic importance compared to the fact that you or some one else can mess up the code in the future. To solve the problem of having many instances:

//The instace
    private static SomeClass _instance = null;
    public static SomeClass instance{
        get{
            if(null==_instance){
                _instance = FindObjectOfType<SomeClass >();
                if(_instance==null){
                    throw new System.ApplicationException("No SomeClass found so no instance can be accessed.");
                }
            }
            return _instance;
        }
    }

    void Awake(){
        if(_instance!= null){
            Destroy(this.gameObject);
            return;
        }

        DontDestroyOnLoad(this.gameObject); //Keep the SomeClass even if loading level.
        _instance = this;
    }
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.