- Home /
Is it better to get an instance in advance?
Currently, about 10 scripts are implemented in a singleton pattern. And when i use the features of the script
AAA.instance.helloA();
BBB.instance.helloB();
Use this way. But is it better to get an instance in advance? As follows
AAA aaa;
void Awake() { aaa = AAA.instance; }
However, this mean I have to add additional declarations every time when I use a singleton class in another script. Or is there any pattern that might help?
This is the best thing you can do for singleton with $$anonymous$$onoBehavours
public class $$anonymous$$ySingletonClass : $$anonymous$$onoBehaviour
{
public static $$anonymous$$ySingletonClass Instance
{
get
{
if (_instance == null)
{
_instance = FIndObjectOfType<$$anonymous$$ySingletonClass>();
}
return _instance;
}
private set {_instance = value;}
}
private static $$anonymous$$ySingletonClass _instance;
void Awake()
{
Instance = this;
}
}
The singleton class uses the contents of the link above. It is similar to the class you wrote. $$anonymous$$y question is when i use a singleton class in another script. AAA.instance.helloA (); just use it like this? Or pre-assigned to variables? (Other additional patterns?)
Yeah just call out to the instance every time, it just accrues more garbage if you were to assign a reference field to it. Even when it is in another namespace it is still more efficient to just call to the root instance.
Your answer
![](https://koobas.hobune.stream/wayback/20220612125701im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
TextMeshPro shows another Input Field above Keyboard Layout 1 Answer
How to remove Unity Ads Plugin? 2 Answers
NLua Whitelist classes from UnityEngine namespace 1 Answer
Programmatically set Sun Game Object 0 Answers
How to make the screenshot and share button not visible in the screen shot it self 0 Answers