Changing between tags on mouse click

I’m trying to swap between two tags on a gameobject when clicked on. The tags are “Selected” and “Deselected”. I am able to change the tag from “Deselected” to “Selected” on each object, but I can’t get them to change back unless EVERY object has been switched to “Selected”. My script is:

            if (Input.GetMouseButtonDown(0))
            {
                RaycastHit hit;
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                if (Physics.Raycast(ray, out hit,
100.0f))
                {
                    if (tag == "Deselected")
                    {
                        hit.collider.transform.tag = "Selected";
                        Debug.Log("Selected");
                    }
    
                    if (tag == "Selected")
                    {
                        hit.collider.transform.tag = "Deselected";
                    }
    
                }

You’re checking tag and then you change hit.collider.transform.tag. Those should be the same.

The problem actually lies in your conditionals. First off, you’re not differentiating between a hit object and one that wasn’t hit. Checking the tag property will fire the script on all objects when your Raycast succeeds regardless of who got hit. Next, you check for the tag being set to Deselected, change it to selected, and then on the very next block, you change it back to Deselected because the tag was just changed to Selected. Use an else if clause here. All told, the changes amount to this:

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

    if (Physics.Raycast(ray, out hit, 100.0f))
    {
        if (hit.collider.gameObject == gameObject)
        {
            if (hit.collider.tag == "Deselected")
                hit.collider.tag = "Selected";
            else if (hit.collider.tag == "Selected")
                hit.collider.tag = "Deselected";
        }
    }
}