How to find if a child belongs to a Transform on RayCast Hit [Updated]

Hi,

I have a raycast which is set to trigger when on a certain object. It does this by detecting the transform name.

However I now need to find out if the transform I have detected is a child of a specific parent transform.

[Updated]Is there a way to get the Root Parents Name of the Transform my RayCast Hit?

Here is my code so far:

if(Physics.Raycast(transform.position, forward, hit, rayCastRange)){
     	if(hit.transform.name == "AttackerTowPoint")
	{
		//Find out if hit.transform is a child of a GameObject called "Attacker"
	}
}

Thanks

Paul

If you want to know if it’s a directly child of “Attacker” you can do like:

if (hit.transform.parent.gameobject.name == "Attacker"){
    // do whatever you want
}

If you want to know if it’s child of child (or at any deeper level) you can try something like this:

Transform t = hit.transform;

bool isChildOfAttacker = false;
while (t.parent != null) {
    t = t.parent;
    if (t.gameobject.name == "Attacker") {
        isChildOfAttacker = true;
        break;
    }
}

if (isChildOfAttacker) {
    // do whatever you want
}

transform.parent returns the parent of a transform.

transform.parent.gameobject.name return the name.