How do I change an objects color by clicking on it during runtime?,How do I change an objects color by clicking on it during run time?

I have a code that works but the color changes no matter where I click on the screen. I would like to make it so that the color of the object only changes when I click on the object.

Here is the code

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

        if (Physics.Raycast(ray, out hit))
        {
            if (Physics.Raycast(ray, 100))
            {
                this.GetComponent<Renderer>().material.color = Color.green;
            }
        }

    }
,I have a code that works but the object changes color no matter where on the screen I click. I would like to make it so that it would change color only when I click on the object

This is the code I have now

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

        if (Physics.Raycast(ray, out hit))
        {
            if (Physics.Raycast(ray, 100))
            {
                this.GetComponent<Renderer>().material.color = Color.green;
            }
        }

    }

You have multiple issues with this script.

First, I believe what is happening is you are changing the color of the material, so every object with that material will be changed. Instead, you should change the material of the object to a different material.

Second, to change the material of the object you clicked on, you would use hit.collider.gameObject.GetComponent<Renderer>().material instead of this.GetComponent<Renderer>().material

I will rewrite your script to incorporate these changes.

public Material selected;
public Material notSelected;
public GameObject selectedObj;
     if (Input.GetMouseButtonDown(0))
     {
         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         RaycastHit hit;
         if (Physics.Raycast(ray, out hit))
         {
               selectedObj.GetComponent<Renderer>().material = notSelected;
               hit.collider.gameObject.GetComponent<Renderer>().material = selected;
               selectedObj = hit.collider.gameObject;
         }
     }

I went ahead and made it so it deselects the last selected object when you select a new one. Make sure you have colliders on your objects. Hope this works!