# Unity3D | Cost of accessing a script via a static reference to the instance

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();


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.

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;
}