Go to previous option in a character editor

Hello everyone. I recently asked how could i switch between objects with a button by instantiating/destroying them as i keep clicking on the Change Hat button and i got this code that works fine:

 public GameObject[] Hats;
 public GameObject Player;
 
 GameObject LastHat;
 int index = 0;
 
 public void InstantiateNextHat()
 {
      GameObject hat = Instantiate(Hats[index], Player.transform);
      
      if (LastHat != null)
           Destroy(LastHat);
 
      index++;
      LastHat = hat;
 
      // If on hat 3, go back to hat 1
      if (index == Hats.Length)
           index = 0;
 }

But i’m stuck when i want to go back to the previous hat. I want to create a new method called Instantiate Previous Hat. I made it similar to the “next hat” method and it works but not perfectly because when i reach hat 3 and click on the “previous” button, it says that index was outside the bounds of the array.

 public void InstantiatePreviousHat()
 {
      index--;
      GameObject hat = Instantiate(Hats[index], Player.transform);
      
      if (LastHat != null)
           Destroy(LastHat);
 
      LastHat = hat;
 
      // If on hat 1, go back to hat 3
      if (index == 0)
           index = hats.Length;
}

I know my mistake might be really dumb but i’m new to Unity so i’m still learning lol.

public GameObject Hats;
public GameObject Player;

    int index = 0;

    public void InstantiateHat(string direction = "NextHat")
    {
        // Choose direction
        if(direction == "NextHat")
        {
            // Set index to direction
            if(index == Hats.Length) 
            {
                index = 0;
            }
            else
            {
                index++;
            }
        }
        else
        {
            if (index == 0)
            {
                index = Hats.Length;
            }
            else
            {
                index--;
            }
        }

        // Destroy old hat
        Destroy(hat);

        // Instantiate new hat
        GameObject hat = Instantiate(Hats[index], Player.transform); 
    }
// To execute use
InstantiateHat();  // For next hat
InstantiateHat("NextHat"); // For next hat
InstantiateHat("LastHat"); // For one before current

I would try something like this. (Not tested) There should be no need to have a copy of the object just to delete the other.