- Home /
This question was
closed Sep 15, 2014 at 10:25 AM by
galaboy for the following reason:
The question is answered, right answer was accepted
Question by
galaboy · Jul 29, 2014 at 03:26 AM ·
ienumerator
trying to run a co routine function gets error
am spawning an object at some random time interval. am using co-routines for that. it shows a error message which i couldn't understand. can some one help me what is the error about. thanks in advance.
using UnityEngine;
using System.Collections;
public class enemySpawner_5 : MonoBehaviour {
public GameObject[] enemies_5;
bool isSpawning = false;
public int minTime = 2;
public int maxTime = 4;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//We only want to spawn one at a time, so make sure we're not already making that call
if(!isSpawning)
{
//making a condition that we can spawn
isSpawning = true;
int enemyIndex = Random.Range(0, enemies_5.Length);
StartCoroutine(spawnObject(enemyIndex, Random.Range(minTime, maxTime)));
}
}
IEnumerator spawnObject( int index, int seconds)
{
//instantiating position
Vector3 position = new Vector3(-1.355466f, 7f, -0.5f);
//instantiating the object
Instantiate(enemies_5[index], position, transform.rotation);
//we have spawned so we could start another spawn
isSpawning = false;
}
}
Comment
Best Answer
Answer by sethuraj · Jul 29, 2014 at 04:08 AM
The problem here is that your Coroutine is not returning/yielding any values here.Try like this
using UnityEngine;
using System.Collections;
public class enemySpawner_5 : MonoBehaviour
{
public GameObject[] enemies_5;
bool isSpawning = false;
public int minTime = 2;
public int maxTime = 4;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
//We only want to spawn one at a time, so make sure we're not already making that call
if(!isSpawning)
{
int enemyIndex = Random.Range(0, enemies_5.Length);
StartCoroutine(spawnObject(enemyIndex, Random.Range(minTime, maxTime)));
//Spawn only once
isSpawning = true;
}
}
IEnumerator spawnObject( int index, int seconds)
{
//instantiating position
Vector3 position = new Vector3(-1.355466f, 7f, -0.5f);
//instantiating the object
Instantiate(enemies_5[index], position, transform.rotation);
//Wait for the random seconds
yield return new WaitForSeconds(seconds);
//we have spawned so we could start another spawn
isSpawning = false;
}
}
thanks for the reply, it was my mistake. as i was at office, in a hurry to leave i forgot to post the error. but thanks for the post. that was a silly mistake. its working good.