Raycast on child gives parent name in hit.transform.name

Hi I cast ray like this.
I have to ignore the layer number 8

var layerMask = 1 << 8;
layerMask = ~layerMask;
				
var ray = Camera.main.ScreenPointToRay(touch.position);
var hit : RaycastHit;
if(Physics.Raycast(ray, hit, 100, layerMask))
{
    print(hit.transform.name);
    if(hit.transform.name == "ChildObjName")
    {
        print("yes child obj");

    }
}

I have assigned the Layer number 8 to Parent Object and I need to cast ray on its child object. but when tap on child object it always gives me parent object name. but i have assigned IgnoreLayer(layer no. 8 ) to parent object.

Also I can tap the other objects that are not child of this parent object.?

Any thing that I can do to detect it?

thanks in advance

if someone is unable to understand. I can explain.

Well, could you not have the child object in a layer that is not layer 8 and then detect the child directly via the raycast ?

Do you have to go via the parent ? Sounds like you are trying to cross the river to get water.

For sure ignoring a layer is a bad idea if you want to detect someting in it.

/Chris

No I need to access the child directly.
the child object is away from parent. I am making the object child due to i have to keep it with parent in complete game play.

If ignoring layer is a bad idea than what could be the best way to do it?

Colliders on child objects are treated as though they are additions to the parent collider (this is what you want for most physics tasks). However, the RaycastHit object also has a field for the collider that was hit. The reported transform is the parent’s transform but the collider is the exact collider that was hit. If you need the transform of the child object, you can use the collider’s transform property, etc.

52 Likes

thanks andeeee it works

1 Like

Works great! Thanks andeeeee :smile:

thanks andeeee it works!!

Thanks!!!

OMG saved my life!

THANK YOU, ANDEEEEEE!!!

Oh my goodness, thank you so much! This finally explains why I couldn’t get the raycast to ignore the parent object! Andeee you’re my hero!

Good to know!

Thanks Andeee!

Thanks andeeeee!

Thanks Andeeeeeeeeeeeeeee!

Thanks andeeeee

just searched for this and andeeeee had the perfect answer ;D

It helps! Thank you

Dude thanks!