I’m working on Android Unity Pro. My game has hundreds of “Find” scripts and I trying to optimize performance. Is there a better way to avoid writing a “Find” script?
Below is a typical "Find’ script in my game. If someone could teach me how to write it more efficiently I’d appreciate it. thanx
function OnTriggerEnter( myTrigger : Collider){
if(myTrigger.gameObject.name == "tum1-2"){
var myTryagain : CameraControls = gameObject.Find("Main Camera").GetComponent(CameraControls);
myTryagain.enabled = false;
}
}
You really shouldn’t have to use GameObject.Find ever, under any circumstances. If you ever find yourself using it, have a good hard look at what you’re doing and make sure there’s not a better way.
For this specific example, is there any reason why you can’t just keep a reference to that ‘CameraControls’ object in your component, instead of finding it every time you enter a trigger?
Having a public reference to your Camera certainly solves this issue as syclamoth has stated. However, you’re actually looking for the CameraControls component, so having a public variable in your class that points to the component is more efficient in this case.
Another approach would be to write an Awake() or Start() function and use gameObject.Find in there, save the results to a class variable (preferably a private variable), and reuse that variable in the OnTrigger. This will ensure your Find() performance hit occurs only once, not every frame you’re in the trigger.
A third way would be to use Camera.main which is a static variable that always points to the “main” camera. http://unity3d.com/support/documentation/ScriptReference/Camera-main.html. Depending on Unity’s implementation, this could also be a bit slower than the techniques mentioned above. You could however combine it with suggestion #2 (the Awake()/Start() caching).
Finally, you should probably avoid the .name == “tum1-2” string comparison as string compares can be slow. You could use the same suggestion of using a public variable to store the object “tum1-2” that you’re looking for. I would think this particular code actually belongs in another class though, one where you know you’re dealing with tum1-2 directly (e.g. should be in a behaviour that attaches to tum1-2) then you can avoid the whole name comparison/object comparison issue all together.
Sorry I didn’t write any code for you but I don’t write in JavaScript and would not want to provide you with non-working code.