Click on mesh

Hi,
i start learning unity but i have a problem.

i have 2 different objects in my scene a Cube and a Sphere with 2 different scripts to detect is the object has been clicked.
but when i click on the cube also the sphere gets hitted?

scene:

the cube code :

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, 100))
            {
                Debug.Log("Clicked on Cube");
            }
        }
    }

sphere code :

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, 100))
            {
                Debug.Log("Clicked on Sphere");
            }
        }
    }

i know its the same code but why do they get triggered both?

thanks in advance,

@quintendc In your both script you are using “Physics Raycast” which means it will trigger click for all colliders in the respective scene.
If you want to use “Physics Raycast”, put an “If” condition as I mentioned in Solution 2.

Solution 1: Instead of “Physics Raycast” you can use “Collider Raycast” for both scripts so that it will trigger the click for the particular collider is hit as I mentioned in the script.

void Start()
{
    coll = GetComponent<Collider>();
}
 void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (coll.Raycast(ray, out hit, 100))
        {
            Debug.Log("Clicked on Cube");
          }
    }

Solution 2: if you are using “Physics Raycast” put an if condition as mentioned below for both respective Scripts(Sphere/Cube).

      if (Physics.Raycast(ray, out hit, 100))
         {
           **if (hit.collider.gameObject.name.Equals("Sphere"))**
            {

                 Debug.Log("Clicked on Sphere");
            }
         }

I hope it will be helpful.