When an object touches the trigger, the trigger wants to know how to deal with this object. Calling GetComponent() several times per frame is not very efficient, I've read. Tags cannot be used because they're not strictly associated with components.
Is there an efficient way to access component code of an object at runtime (such as from OnTriggerStay). For example, some game engines would have something like a collider.gameObject.userData object which can be cast at runtime yielding decent performance (although that's somewhat nasty as well). The userData would be a class that caches all the components at load time, for example.
You're asking how to avoid GetComponent(), right?
GetComponent returns the component instance of something somewhere. To avoid calling GetComponent you must to get the component and store it somewhere more accessible.
Storing the component in general
Since you don't really know what you're colliding with, simply storing the collided object may not work for you. If you only have certain things that can collide with this, then you can store and check against those. If your use case promotes recurrent collisions, you could still cache the last object & component that were collided with and when a new collision occurs, check and use them if they're the same, otherwise chuck them and GetComponent.
Static = everybody knows about it
Using statically scoped functions and variables would make things even easier, but such scripts may need to be a little smarter than the average script because static functions cannot access the public Monobehaviour-local variables that would refer to the instance to which the script is attached. If there's only a few objects, this is viable and potentially more efficient solution as a static script with a static, quicker-to-search container (HashSet for example) that contains references to the things you care about colliding with, can be quickly searched, which is likely less overhead than getComponent;
You say you're concerned about calling GetComponent every frame. Why would you do that then? You could avoid OnTriggerStay by storing the component of the object OnTriggerEnter and removing the it OnTriggerExit, performing whatever it is you were doing OnTriggerStay within Update to each component stored and this would call GetComponent only OnCollisionEnter and maybe OnCollisionExit, but not every frame.
answered Oct 22 '10 at 08:28 PM