Home > OS >  Transform.parent is not working to access the grandparent
Transform.parent is not working to access the grandparent

Time:11-09

I am attempting to find the rigidbody2D assigned to the grandparent of the object that the script is assigned to,but Transform.parent.parent is not working to do this,

transform.parent.parent.gameObject.TryGetComponent(out Rigidbody2D parent);

this is my code, but it won't get the rigidbody, there is one there because if I set the variable to be public I can assign it in the editor manually, but that won't work in this case for the game, is there any other way to access the grandparent object?

CodePudding user response:

Instead rather simply use GetComponentInParent

Returns the component of Type type in the GameObject or any of its parents.

(Since version 2021) Optionally pass in true to include inactive objects and disabled components

var rb = GetComponentInParent<Rigidbody2D>(true);
if(rb)
{
    ...
}

CodePudding user response:

If your Grandparent object is the top item in the hierarchy then you can use transform.root to reference it.

  • Related