0
votes

I want to instantiate new prefab in array and delete the old one when user click on the next button or on previous button.

I have the array of gameobject prefab something like this:

public GameObject[] prefabMoles = new GameObject[3];
 GameObject[] moles = new GameObject[3];
 
 void Start () {
 
     for(int i = 0; i < prefabMoles.Length; i++)
     {
         moles[i] = (GameObject) GameObject.Instantiate(prefabMoles[i], new Vector3((i-1)*5, 0, 0), Quaternion.identity);
     }
 
 }

So now I want to add button on canvas which will be next character and previous will return back one number in array.

For example: I have Moles array and i instantiate moles[2]; On click on next button I want to destroy moles[2] and instantiate moles[3].

When we are on moles[3] and when we click previous we must destroy moles[3] and instantiate moles[2].

It would be great to have some effect of spawn new one but doesn't matter. And then when instantiate the new the button must popup for unlock or for select if the character is unlocked.

Thank you so much community for help if that is possible.

1

1 Answers

1
votes

If what you want to do is have your button create a new and destroy the old you can do this one function that can be added to the button's action.

It will look something like:

int currentIndex = 0;
GameObject currentObject;

void Start()
{
     //Instantiate initial object
    currentObject = Instantiate(Moles[currentIndex]);
}

public void Previous()
{
    Destroy(currentObject);
    currentIndex --;
    currentIndex = currentIndex < 0 ? Moles.Length : currentIndex;
    currentObject = Instantiate(Moles[currentIndex]);
    SpawnEffects();
}    

public void Next()
{
    Destroy(currentObject);
    currentIndex ++;
    currentIndex = currentIndex > Moles.Length ? 0 : currentIndex;
    currentObject = Instantiate(Moles[currentIndex]);
    SpawnEffects();
}

void SpawnEffects()
{
    //put your desired Effects
}

Essentially you are keeping track of what has been created and what is the next item that you want to make.