Cashing GameObject before GetComponent

Hi guys!

I am a little bit confused, In every tutorial I see, people using this method

GameObject someObject = GameObject.Find("SomeObject");
ScriptName someScript = someObject.GetComponent<ScriptName>();

and not this

ScriptName someScript = GameObject.Find("SomeObject").GetComponent<ScriptName>();

What is the better method and why?

Thanks!!!

It’s situation dependent. Caching an object will consume a small amount of RAM. If you do this many times it could have an impact. If you don’t need to cache it, don’t.

Find is expensive, GetComponent is less expensive. This is why Find is usually performed in Start(). If you need repeat GetComponent calls it may be better to do it from a cached object than Finding it each time, which is highly inadvisable in Update().