- Home /
How Can I Get the Parent GameObject from Within a Component (C#)
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.
Answer by stng · Jun 29, 2018 at 04:43 AM
You can use Component.gameObject
Link: https://docs.unity3d.com/ScriptReference/Component-gameObject.html
Answer by aldonaletto · Nov 20, 2011 at 03:43 PM
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>();
Answer by DaveA · Nov 20, 2011 at 03:32 PM
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.
So it sounds like I should add the "stuff that happens" on collision to the Trap, but that I should modify the collision boundaries directly on the CapsuleCollider ins$$anonymous$$d of trying to alter them through the Trap component?
Your answer
![](https://koobas.hobune.stream/wayback/20220613050609im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do you prevent a base class from being addable as a script without making it abstract? 0 Answers
Capsule doesnt collide capsule properly 0 Answers
RayCast can't detect GameObject at Player's feet 0 Answers
Adding a rigidbody and capsule collider to my player makes it teleport along the Y axis while moving 0 Answers
RequireComponent script order 2 Answers