- Home /
Different array value at different times
I have a GameObject array with a number of different objects. I want - at different times - to instantiate the object stored in GameObject[0], then the one stored in GameObject[1] and so on.. i've created this script but it doesn't work..
var enemies : GameObject[];
function Update () {
if ((Time.time > 0) && (Time.time < 5)){
enemies = enemies[0]; // i think the problem is in this line
GenerateEnemy ();
}
if ((Time.time > 5) && (Time.time < 10)){
enemies = enemies[1];
GenerateEnemy ();
}
}
function GenerateEnemy (){
Instantiate(enemies, Vector3(0,0,0), transform.rotation);
}
Anyone knows where i'm wrong?
Answer by AlucardJay · Jul 30, 2012 at 12:29 PM
You are trying to store different things in the same place. Try :
EDIT :
var enemies : GameObject[];
var currentEnemy : GameObject;
var spawnTimer : float = 0.0;
function Update () {
if ((Time.time % 10.0 > 0) && (Time.time % 10.0 < 5)){
currentEnemy = enemies[0];
}
if ((Time.time % 10.0 > 5) && (Time.time % 10.0 < 10)){
currentEnemy = enemies[1];
}
spawnTimer += Time.deltaTime;
if (spawnTimer > 1.0){ // enemy is spawned every 1.0 seconds
GenerateEnemy();
spawnTimer = 0.0;
}
}
function GenerateEnemy (){
Instantiate(currentEnemy , Vector3(0,0,0), transform.rotation);
}
(with original script) Note that this will Instantiate an enemy (type 0 or type 1) every frame.
add a counter/timer. then when the timer is reached, spawn and reset the timer.
I have edited the answer that now takes into consideration spawning the enemy once every 1 second, and also continues to spawn different types of enemy after 10 seconds.
I have edited the answer. A timer is just a var you set yourself. See my answer :
var spawnTimer : float = 0.0;
This is just a variable to hold the value for reference. Then in Update, increment this value with :
spawnTimer += Time.deltaTime;
Now the timer goes up in seconds. You can check this by adding
Debug.Log( "spawnTimer = " + spawnTimer );
Then, if you want to reset the timer, use
spawnTimer = 0.0;
That's about it =]
search google to read more, or see how other people are implementing timers : http://www.google.com/search?btnG=1&pws=0&q=unity+timer
Your answer
Follow this Question
Related Questions
Instantiating from an object that's in an array 1 Answer
What is the best way to instatiate an array of connected GameObjects? 0 Answers
using destroy with an array of GameObjects (C#) 1 Answer
Instantiating gameobject variables (in an array) from a different script 1 Answer
Instantiate large block maps 2 Answers