transform.SetParent() not setting the object I want as parent.

Hi everyone!

I’m having a problem with transform.SetParent().

Basically, I want my character to have a precise object of the car he is in as a parent.
My car has multiple child objects, themselves having children too. The specific object I want as a parent is the child of another child of the car (I hope this is clear enough). I’m trying to cast a ray from the character towards the ground to detect what is just under him and set what it hits as parent.

But despite my use of raycast and layermask, it is not working. My car has its layer set as “Ignore Raycast”, and the only object I want as a parent has the layer I added. But whenever I call my raycast to detect the object I’ll set as a parent, the hit infos give me the car object, despite its layer.

Does anyone have an idea to fix this? Thanks a lot!

Why would you want to do some complex raycasting to find a child of the car object, in the first place?

Why not simply have this handled in your Car’s script, with a reference to its child object that the player needs to be parented to? Are these components moving constantly & switching what’s underneath? If they’re static, just store a reference to them somehow.

//Car.cs
public GameObject PreciseObjectToParentTo; //Assign this in the Inspector
//In Code
playerObject.SetParent(PreciseObjectToParentTo);

Something more manageable, like that?

My character can be inside and outside the car, hence the fact that I want him to be a precise child of the car when he is Inside it.

But the solution hexagonius linked worked perfectly: using hit.collider.transform instead of hit.transform in order to not get the parent of the object you hit but the object itself.