I have a GameObject that will share a common feature with a bunch of other GameObjects. When an NPC runs into it, I want to perform an action.
I’ve started scripting a class called Trap. My intention was to require a CapsuleCollider, and then use variables inside the Trap class to control some of the relevant parameters of the CapsuleCollider.
The problem that I’m having is that if I want to do this then I need access to the CapsuleCollider that I’m requiring. I’m very new to Unity and I’m having difficulty figuring out what I need to do to get to the GameObject that owns this particular instance of the component (or it’s sibling components).
Any help is apprecaited.
Child and component aren’t the same thing: components are added directly to the GameObject, while children are complete GameObjects whose transform.parent property is set to the parent Transform. To get a component of a GameObject, you use GetComponent:
var capsule: CapsuleCollider = GetComponent<CapsuleCollider>();
Or, in C#:
CapsuleCollider capsule = GetComponent<CapsuleCollider>();
This instruction gets the CapsuleCollider component of the object to which the script is attached. If you need to get the CapsuleCollider of another object, you must have a reference to it - its transform, gameObject, collider etc.
var otherObj: Transform; // drag the other object here
var capsule: CapsuleCollider = otherObj.GetComponent<CapsuleCollider>();
You can use Tags and use http://unity3d.com/support/documentation/ScriptReference/GameObject.FindWithTag.html or keep track of all the instances in an array or list or something. And remember that when collision is detected, it gives you the object that collided, and you can get at its components from that.
(current_component as MonoBehaviour).gameObject