Somehow i can`t manage to make this enemys spawn with timer.
THey do spawn as soon as i kill one, but it happens INSTANTLY, despire WaitForSeconds being in script.
Need an idea how to make new guy appear like 2 seconds after you kill the one before him, not instantly.
Any help would be appritiated.
using UnityEngine;
using System.Collections;
public class SpawnEnemy : MonoBehaviour
{
public GameObject[] EnemyTypes;
ScoreManager scoreManager;
void Awake()
{
scoreManager = GameObject.Find("GameManager").GetComponent<ScoreManager>();
}
void Update()
{
if (scoreManager.inPlay)
{
if (scoreManager.EnemyCount <= 3)
Spawn();
}
}
void Spawn()
{
Debug.Log("SPAWN!");
Vector3 spawnV = new Vector3(Random.Range(-6, 6), Random.Range(-3, 3), 0);
int s = Random.Range(0, EnemyTypes.Length);
Instantiate(EnemyTypes~~, spawnV, Quaternion.identity);~~
//Instantiate(EnemyTypes[0], Vector3.zero, Quaternion.identity);
scoreManager.EnemyCount++;
StartCoroutine(“Wait”);
}
IEnumerator Wait()
{
yield return new WaitForSeconds(2);
}
}
You aren’t using the co-routine properly. Try this instead (Untested):
using UnityEngine;
using System.Collections;
public class SpawnEnemy : MonoBehaviour {
public GameObject[] EnemyTypes;
public float spawnRate = 2f; //probably don't want to hardcode that
ScoreManager scoreManager;
float timeSinceLastSpawn = 0f;
void Awake()
{
scoreManager = GameObject.Find("GameManager").GetComponent<ScoreManager>();
}
void Update()
{
timeSinceLastSpawn += Time.deltaTime;
if (scoreManager.inPlay)
{
if (scoreManager.EnemyCount <= 3 && timeSinceLastSpawn >= spawnRate)
Spawn();
}
}
void Spawn()
{
Debug.Log("SPAWN!");
Vector3 spawnV = new Vector3(Random.Range(-6, 6), Random.Range(-3, 3), 0);
int s = Random.Range(0, EnemyTypes.Length);
Instantiate(EnemyTypes~~, spawnV, Quaternion.identity);~~
~~ //Instantiate(EnemyTypes[0], Vector3.zero, Quaternion.identity);~~
~~ scoreManager.EnemyCount++;~~
~~ timeSinceLastSpawn = 0f;~~
~~ }~~
}
@Silvermurk
Replace Spawn() in Update() to your wait coroutine like :
void Update()
{
timeSinceLastSpawn += Time.deltaTime;
if (scoreManager.inPlay)
{
if (scoreManager.EnemyCount <= 3 && timeSinceLastSpawn >= spawnRate)
StartCoroutine(Wait());
}
And then call Spawn function in that coroutine like :
IEnumerator Wait()
{
yield return new WaitForSeconds(2);
Spawn();
}
This will pretty much do your job. Good luck.