FindObjectOfType<> vs Cache Referencing

Hi, I would like to know about what is the difference between these two codes which gives the same outcome but I’m curious though.

private GameStatus gameStatus;

void Start()
{
     gameStatus = FindObjectOfType<>();
}

void RestartGame()
{
     gameStatus.ResetGame();
     SceneManager.LoadScene(0);
}

vs

void RestartGame()
{
     FindObjectOfType<GameStatus>().ResetGame();
     SceneManager.LoadScene(0);
}

1 Like

Hi Ishtiaq01,

Find methods such as Find and FindObjectOfType are one of the slowest methods in Unity, and it is not recommended to call them in Update. If we access the GameStatus object only once during the lifetime of the object where we try to access the GameStatus object, it is not necessary to cache the reference to the GameStatus object. However, if we accessed it more than once, we would have to call the FindObjectOfType method multiple times. In that case, caching makes sense to increase the performance of our game.

Did this answer your question? :slight_smile:


See also:

2 Likes

So we do not need to use Cache Referencing always but to make everything simpler and boost the performance and productivity it’s much better to have it in the beginning than to call it every time we need to use the object right?
And if FindObjectOfType<>() is the slowest method in Unity then isn’t it good to use the Referencing in the Inspector and drag-drop method which we have been using for a long time. If so then what is the difference between these two ways of referencing an object?
Thank you in advance @Nina

If we access the object only once, there will not be any difference in the performance. Maybe we’ll never have need the object. In that case, calling the Find method would be a waste of resources.

You are right. That would be more performant.

Unfortunately, it is not always possible to assign the reference manually. For instance, if you instantiate an enemy during runtime, it might be that the enemy depends on something in the scene. In that case, the enemy object would have to look for an object during runtime.

Another example would be: Imagine you had lots of different objects, and they all needed a reference. It sometimes could make sense to call FindObjectOfType to avoid missing something.

As you can probably see, it depends. There is no universal answer, so you’ll have to make your own decisions depending on the actual situation in your game.

2 Likes

I really appreciate the answer :slight_smile: Thank you for explaining it perfectly. Couldn’t have found a better answer than this. Wishing you a beautiful day/night.

1 Like

You’re welcome. :slight_smile:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms