How to get only one object to select at a time (in game)?

So I have several blocks , with a script attached that changes between two materials when clicked on. The challenge I’m having is getting only one block to change materials at a time, so that when I select another block, any previously selected will deselect. I’m just using an array to cycle through the two materials.

    using UnityEngine;
    
    public class ColorEnChange : MonoBehaviour {
    
        public Material[] material;
        Renderer rend;
        public int index = 0;
    
        void Start()
        {
            rend = GetComponent<Renderer>();
            rend.enabled = true;
            rend.sharedMaterial = material[0];
        }


        private void OnMouseDown()
        {
    
            if (material.Length == 0)
            {
                return;
            }
    
           
            if (Input.GetMouseButton(0))
            {
                index += 1;
    
                if (index == material.Length + 1)
                {
                    index = 1;
                }
                rend.sharedMaterial = material[index - 1];
            }
        }
       
    }

Picture: Too many blocks selected. Want blocks that are selected to deselect when another clicked on (in game).

Try using a singleton. It keeps track of the last selected renderer, and deselects it every time you select a new renderer.

.

using UnityEngine;
 public class ColorEnChange : MonoBehaviour {
 
     public Material[] material;
     public static Renderer Selection;
     Renderer rend;
     public int index = 0;
 
     void Start()
     {
         rend = GetComponent<Renderer>();
         rend.enabled = true;
         rend.sharedMaterial = material[0];
     }


     private void OnMouseDown()
     {
 
         if (material.Length == 0)
         {
             return;
         }
 
        
         if (Input.GetMouseButton(0))
         {
             index += 1;
 
             if (index == material.Length + 1)
             {
                 index = 1;
             }
             rend.sharedMaterial = material[index - 1];
             if (Selection) {
                  Selection.rend.sharedMaterial = whatever material deselected is;
             }
             Selection = rend;
         }
     }
    
 }