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.