- Home /
Optimisation - When to use Global variables or GameObject.Find() ?
Hi,
I was wondering about this as I've heard that if you are regularly referencing objects in a scene then it is better/more efficient to use Global variables rather then GameObject.Find() in real-time. Can anyone clarify this, and provide any more information on when to use each of these and how/where to assign them for maximum optimisation?
Thanks
Answer by ScroodgeM · Jul 17, 2012 at 01:43 PM
best way for optimization is:
if you use GameObject.Find() more then once for some object, then you should use it once and store a link to it for future use.
you can store it in private variable, on in public static for other components can access it too
Hi Scroodge$$anonymous$$,
Really, so you're saying that using GameObject.Find() is more efficient than pre-caching it using a Global variable and dragging in from the Inspector beforehand? I was under the impression that doing the latter eli$$anonymous$$ated the work done to Find the object whilst running?
Thanks
in any program$$anonymous$$g language any method that needs to check large array of objects is expensive. especially it uses a string comparison.
GameObject.Find() should check all objects until it finds one that matches condition.
just imagine situation where in first case you should find a man named '$$anonymous$$ike' in a crowd of thouthands people (where can be more then one '$$anonymous$$ike'), and in the second you have an end of rope marked '$$anonymous$$ike' and the other end of this rope is attached to $$anonymous$$ike you need