Select child object by touch

Hi all,
First of all sorry about my english i know its sux ;(
My problem when i touch the child object ( its a pillow on sofa) collider.transform.name always returning parrents name.Im trying to do change selected object color. Color change script working good but like as i said its always returning parrent. An example i want to change only pillows colour on sofa but it changes sofa colour not the pillows. Im new in unity. Tyvm for ur help.

public class objectSelect : MonoBehaviour {
    public Text tex;
    public Text tex2;
    public Transform obj1;
    public string rr;


    void Start () {
   
    }
   

    void Update () {
    

        Touch touch = Input.touches [0];
        Vector3 pos = touch.position;


        if (Input.touchCount > 0 && touch.phase == TouchPhase.Began) {


            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay (pos);

            Vector3 planePoint = ray.GetPoint(0.0f);
           

            if (Physics.Raycast(ray,out hit))
            {

                obj1 = hit.transform;
                tex.text = obj1.transform.gameObject.GetInstanceID().ToString();
                tex2.text = hit.collider.transform.name;
                RR=obj1.transform.gameObject.GetInstanceID().ToString();

            }
        }
           
    }

    public string getselectedObj()
    {
        return obj1.transform.gameObject.GetInstanceID().ToString();
    }
    public string r()
    {
        return "rrrrrR";

    }
    public string RR{
        get
        {
            return rr;
        }
        set
        {
            rr = value;
        }
    }
}

could you expound a little on what your scene has in it? 2d, 3d etc.

also might want to look at:

:stuck_out_tongue:

Its 3d. Scene has just 1 sofa and 2 pillows in it. Sofa and pillows has seperate box colliders

are the pillows within the sofa’s collider bounds (the green wireframe when you have the sofa selected)?

raycast returns the first thing it hits, if the pillows are within the sofa you’ll be hitting it first.

There are a couple of ways around this:

If you never want to select the sofa, you can have the pillows on one layer and the sofa on a different layer and specify the pillow layer in the raycast.

If you want to be able to select sofa and pillows, you can use RayCastAll which will return a list of colliders along that ray, not just the first one, but you’ll need to do more work to figure out which you should be working with.

You can change the collider on the sofa to more correctly represent it’s shape, i.e. the sofa becomes a compound object with children representing the back/seating/ends each with their own box colliders.

1 Like

Here is my hierarchy