Cycle trought array of objects

Hi all, I need a method to cycle trought an array of objects that I instatiate at runtime, at the moment I have this which instatiate only the first element in the array:

function OnMouseDown(){
    var instance : GameObject = Instantiate(models[0],,Quaternion.identity) as GameObject;

but how do I make it so that everytime I click a new element is instatiate and the previous one is destroyed?

Sorry I am not a programmer
Many thanks in advance!

#pragma strict
var models : GameObject;
var instance : GameObject;
var cycleIndex : int;

   function Start() {
      models = Resources.LoadAll.<GameObject>("Objects");

   function OnMouseDown() {
      if (instance) {
      instance = Instantiate(models[cycleIndex],,Quaternion.identity) as GameObject;
      cycleIndex += 1;
      if (cycleIndex+1 > models.Length) {
         cycleIndex = 0;

I put the “instance” outside of the local scope, so it is retained, then you can simply destroy instance before you make a new one.

And to cycle through the indexes you need to count it yourself and reset it back to 0 when it’s needed (as demonstrated with cycleIndex).

We check if cycleIndex+1 is above array.Length because Length returns 5 for 5 items, but array index will count 1 item as index[0], and so on.