- Home /
How to Instantiate a Different Game Object After Getting to the End of an Array?
I have an array. It randomly chooses a number, let's say from 1 to 20 for example.
A game object is instantiated every time a button is pushed. Fine no problem.
Let's say the array has 20 elements for example. After I push a button, I need a different game object to instantiate.
The problem is the new game object is instantiating when the last game object of the array is instantiating.
Basically, the last game object in the array and the different game object are instantiating at the same time.
What needs to happen is when the user pushes the button, the last game object of the array is instantiated.
Then, the next time the user pushes the button the different game object needs to be instantiated. Not at the same time as the last element in the array.
I've tried bools and other ridiculous ideas that didn't work.
I know it's something very simple, but have no idea.
Any ideas how to fix this problem?
Thanks!
There's not much to show really. When a button is pushed, let's say the spacebar, I instantiate one prefab at a time from spawnStuff().
When i++ is at the end of the array eg all the array's elements have been spawned, spawnOneDifferentObjectEndOfArray() is called when the last element of the array is spawned.
spawnOneDifferentObjectAtEndOfArray() needs to be called on the Next push of the spacebar, not when the last element of the array is spawned.
void spawnStuff(){
// Spawn Stuff from Array Here
spawnOneDifferentObjectAtEndOfArray();
}
void spawnOneDifferentObjectAtEndOfArray(){
// Instantiate Here
// The problem is here
// This method is getting called at the same time as the last game object // is instantiated
}
Are you detecting when you reach the end of the array? $$anonymous$$aybe something along these lines would work?
if the space bar is pressed:
if the array isn't empty:
spawn stuff;
else:
spawn that thing at the end;
And then in SpawnStuff() you need to check for the array being empty:
spawn something from the array;
if that was the last thing in the array:
the array is empty;
Answer by saschandroid · Jan 08, 2016 at 11:34 AM
int m_index = 0;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if ( m_index < firstArray.Length)
{
// spawn firstArray[m_index]
m_index++;
}
else
{
// spawn otherObject
}
}
}
Your answer
Follow this Question
Related Questions
Save Gameobject in Array 1 Answer
Want replace a current object with one inside array the object being replaced with is prefab 1 Answer
Instantiate from array into array? 2 Answers
Instantiating a gameObject in an array is not working for me 1 Answer
Referencing an instantiated object with a global variable 0 Answers