can I use .gameObject freely within a monobehaviour to access the game object it is attached to or should I reference it once and use the reference afterwards?
I ask this because there are some methods like .getcomponent and object.find that have such bad performance that they should only be called once to save them to a reference and then use the reference thereafter.
So the question is: can I use .gameObject freely or is it similar to getcomponent performance wise and should I use it only once to create a reference?
I donât think things like âGetComponentâ or â.gameobjectâ really relate to â.findâ. Though the first two are slightly slower then having a reference directly it will not be as slow as â.findâ and wont create garbage like â.findâ.
I think that since 5.0 (I might be wrong) they automatically cache certain Monobehaviour variables. I took the habit of caching transform to a private variable but I freely use .gameObject pretty much everywhere and I never had an issue.
Of course calling it 4000 times per Update might become an issue.
If you know youâre going to reuse that variable a lot then itâs worth using the 4bytes of memory for the reference.
I would certainly not lump GetComponent together with GameObject.Find(). GetComponent can be called thousands of times per frame with no perceptible performance impact.
The .gameObject property is likely even better than that. While its implementation is not really known, I canât imagine itâs much worse than a hashtable lookup.
If youâre approaching this from the angle of âhey I heard this is badâŚâ Instead of âI profiled my game and noticed this is badâ youâre probably prematurely optimizing.
At risk of going on a tangent, Iâve seen performance issues calling GetComponent a few dozen times in Start during prefab instantiation. Most prominently the first time the prefab has been instantiated. Iâve also seen GetComponent called hundreds of times per frame in Update without causing any significant performance issues. I would have investigated this further, but replacing GetComponent calls in Start with inspector references resolves the issue, and I tend to move on when a problem gets solved rather than go down the rabbit hole of further investigation
On the original question, Iâve never seen the profiler point to any of my code using .gameObject, and I use it quite frequently. Iâd suggest just using it and only doing potentially better optimization if it actually does become a problem.