- Home /
Is it costly to get a singleton instance each frame ?
Consider this :
private void Update()
{
UpdateUI();
PlayerInfo.GetInstance().planetsVisited = PlayerInfo.GetInstance().score / planetRate;
}
Does the GetInstance() function do a similar thing as say GetComponent()
Is it more optimized to make a cache like private PlayerInfo m_playerInfo;
and get it at Start() ?
Depends what your GetInstance method does? We can't possibly know. Can you share that also? A singleton's purpose is to return a reference to a type that you have only once in the lifetime of your application.
This reference is usually a cached field, so it should be very fast.
Answer by Namey5 · Aug 26, 2020 at 11:52 AM
This depends on how the singleton is setup and what GetInstance() does. For the majority of things though, you should be caching the instance;
private Singleton m_Instance;
public Singleton Instance => m_Instance;
private void OnEnable ()
{
if (m_Instance && m_Instance != this)
{
enabled = false;
return;
}
m_Instance = this;
}
private void OnDisable ()
{
if (m_Instance == this)
m_Instance = null;
}
Using a property and member variable like this provides access safety and allows you to still publicly access the instance as though it were a variable.
Your answer
Follow this Question
Related Questions
How do I stop a singleton from trying to load itself again when I change scenes? 1 Answer
Prefab Instances all have separate Scales? 0 Answers
Would setting this static cause a memory leak? 1 Answer
Avoid NullReferenceException with Singleton 3 Answers
Singleton instance accessed in coroutine always null 1 Answer