Writing a script to select one object at a time.

I’m trying to write a script which allows the player to select one object at a time. The way I have chosen to tackle this is to attach the following code to each selectable object:

public class CharacterScript : MonoBehaviour {

    public bool selected = false;
    public GameObject reticule;
    public Transform reticuleOrbiter;
    public GameObject[] team;
    
    void OnMouseDown()
    {
        team = GameObject.FindGameObjectsWithTag("Player Character");

        for (int i = 0; i < team.Length; i++)
        {
            Debug.Log("Player Number " + i + " is named " + team*.name);*

selected = false;
}
selected = true;
Instantiate(reticule, reticuleOrbiter.position, reticuleOrbiter.rotation);
}
}
Obviously, this isn’t working, but I hope you all can see what I am driving at. At present selecting objects works fine, but unselecting previous objects isn’t happening. In case you haven’t figured it out, I am in the very, very early stages of learning to code, and if something doesn’t work I am never sure if I made a typo, or am fundamentally just feeding the computer gibberish. Thanks for your help!

In your case, it would be easier to use Raycasts instead of OnMouseDown function.

I haven’t tested the following script

private Collider lastSelected = null ;

 private void Update()
 {
    if( Input.GetMouseButtonDown(0) )
    {
            RaycastHit hitInfo;
            Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
            if ( Physics.Raycast( ray, out hitInfo, 100) )
            {
                if( lastSelected == null || hitInfo.collider.GetInstanceID() != lastSelected.GetInstanceID() )
                {
                     // Blur last selected
                     lastSelected = hitInfo.Collider ;
                     // Focus new selected
                }
           }
    }
}

If you still want to keep your Selectable Object approach, you can use a static member so that you don’t need to unselected every other object when one is selected.

public class CharacterScript : MonoBehaviour
{ 
     public static GameObject selected;
     public GameObject reticule;
     public Transform reticuleOrbiter;
     public GameObject[] team;
     
     void OnMouseDown()
     {
         selected = gameObject;
         Instantiate(reticule, reticuleOrbiter.position, reticuleOrbiter.rotation);
     }
 }