Selecting between two objects

Can someone explain to me how to make a simple selection system? What I have now is ray casting method that lets me select between two objects. But, the problem is that I can’t really select between the two correctly. For example: if I have Object A and Object B and I select Object A and than Object B I can’t select Object A again; same problem if i select in reverse order.

void OnMouseDown()
    {
        GameObject theGameManager = GameObject.Find("GameManager");
        GameManager GameManagerScript = theGameManager.GetComponent<GameManager>();

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

        if (Physics.Raycast(ray, out hit))
        {
            // check if PlayerUnit 1 is selected
            if (hit.collider.name == "PlayerUnit 1")
            {
                Debug.Log("PlayerUnit 1 selected");

                GameManagerScript.is_PlayerUnit_1_Selected = true;
                GameManagerScript.is_PlayerUnit_2_Selected = false;

                GameManagerScript.PlayerUnit1.GetComponent<Unit>().enabled = true;
                GameManagerScript.PlayerUnit1.GetComponent<UnitPath>().enabled = true;
                GameManagerScript.PlayerUnit2.GetComponent<Unit>().enabled = false;
                GameManagerScript.PlayerUnit2.GetComponent<UnitPath>().enabled = false;
                return;
            }
            // check if PlayerUnit 2 is selected
            else if (hit.collider.name == "PlayerUnit 2")
            {
                Debug.Log("PlayerUnit 2 selected");

                GameManagerScript.is_PlayerUnit_1_Selected = false;
                GameManagerScript.is_PlayerUnit_2_Selected = true;

                GameManagerScript.PlayerUnit1.GetComponent<Unit>().enabled = false;
                GameManagerScript.PlayerUnit1.GetComponent<UnitPath>().enabled = false;
                GameManagerScript.PlayerUnit2.GetComponent<Unit>().enabled = true;
                GameManagerScript.PlayerUnit2.GetComponent<UnitPath>().enabled = true;

                return;
            }
        }
    }

What happens after you’ve clicked one or the other?

Does the collider get turned off?

We don’t know what happens in the Unit and UnityPath OnEnable/OnDisable code. Or if any other code reacts to this event. As is the code you’re showing makes sense for the most part…

Also, you may want to consider an approach that doesn’t rely on magic strings like that so much. Turn GameManager into a Singleton so you can quickly get a reference to it. Check if the objects are equal rather than if the names match. Store an ‘selectedPlayer’ property rather than a ‘is_such_and_such_selected’. Use collections instead of numerous variables named var1, var2, etc.