GetComponentInParent... Is this a bug or what exactly is wrong with this.

This gives me a Vector3:

hitone[i].collider.GetComponentInParent<Rigidbody2D>().transform.position

While this gives me a Vector 2: (What I want)

hitone[i].collider.GetComponentInParent<Rigidbody2D>().position

This gives me .this object name rather than the parent:

hitone[i].collider.GetComponentInParent<Transform>().name

While this gives me the name of the parent: (What I want)

hitone[i].collider.GetComponentInParent<Rigidbody2D>().name

I did waste A GOOD AMOUNT OF TIME dealing with these things, so I would like to know what exactly is wrong with the first approaches :smile:

The first two items are normal behaviour. You can cast a Vector3 to a Vector2, unity will simply drop the z component. Transform.position is a Vector3.

Not sure what’s happening in the second example.

Note that Collider2D.attachedRigidbody will also give you what you want.

Unitys transform component is the same for 2D and 3D objects, so every object has a vector3 as its transform position.
for the second one, i’m not sure but i think one of unity’s ways to access child-transforms is ‘Transform in transform’ (like foreach (Transform t in transform) {t.doSomething();} ), so you’re actually re-accessing the child.

GetComponentInParent returns the component attached to the given GameObject or any of its parents. Every GameObject has a transform so in that context you’ll always get back the transform of the GameObject you’re looking at. I would imagine in your second case the parent has a Rigidbody2D component but the GameObject with the collider does not.

In your first example - transform.position is always a Vector3 regardless of how you get to it. Rigidbody2D.position is a Vector2 because it only deals in 2 dimensions.

So, no. Not a bug :slight_smile:

3 Likes

I always thought parent was a reference to the hierarchy, not “closest object above with this game Component”.
For some reason, suddenly, I have many things to fix. :smile:

Thanks for the answers!

There is your answer. I personally never use GetComponentInParent. As a general rule my GameObjects are not allowed to know about their parents, except in a very general SendMessageUpwards or ExecuteEvents.ExecuteHeirarchy kind of way.

One way dependency is much easier to manage. (ie parents can know about their children, but children cannot know about their parents).

1 Like

The name is certainly a bit misleading. The most straight-forward way to do what you want would be this

transform.parent.GetComponentInParent<Component>();

While, of course, checking that your transform actually has a parent in the first place.

3 Likes