Reputation: 195
I'm new to Unity and I was just creating a simple galaxy shooter game where I want the enemies to be spawned only when the the player comes to existence. So I have created a coroutine that checks for the playerExists
condition, if it turns out to be true
, it should further proceed in spawning the enemies every 5 seconds. But for some reason, it spawns just one enemy. Am I missing anything here ?
Below is my SpawnManager where the spawning behaviour is controlled.
public class SpawnManager : MonoBehaviour {
[SerializeField]
private GameObject _enemyShipPrefab;
[SerializeField]
private GameObject[] _powerUp;
UIManager _uimanager;
// Use this for initialization
void Start () {
_uimanager = GameObject.Find("Canvas").GetComponent<UIManager>();
StartCoroutine(SpawnPowerUps());
StartCoroutine(SpawnEnemy());
}
IEnumerator SpawnEnemy(){
while (_uimanager.playerExists == true)
{
Vector3 position = new Vector3(Random.Range(-8.23f, 8.23f), 5.7f, 0.0f);
Instantiate(_enemyShipPrefab, position, Quaternion.identity);
yield return new WaitForSeconds(5.0f);
}
}
}
Below is my UIManager where i control the existence of the player.
public class UIManager : MonoBehaviour {
// Use this for initialization
public bool playerExists = false;
public int playerScores = 0;
public Sprite[] lives;
public Image playerLivesImagesToBeShown;
public Text playerScoreToBeShown;
public Image titleImage;
public GameObject playerPrefab;
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && playerExists == false){
titleImage.gameObject.SetActive(false);
Instantiate(playerPrefab, new Vector3(0, 0, 0), Quaternion.identity);
playerScores = 0;
playerScoreToBeShown.text = "Score : 0";
playerExists = true;
}
}
public void updateLives(int livesToView ){
playerLivesImagesToBeShown.sprite = lives[livesToView];
if(livesToView == 0){
playerExists = false;
titleImage.gameObject.SetActive(true);
}
}
Upvotes: 1
Views: 61
Reputation: 5150
At the first glace of your code (and the described problem) i would say, your SpawnEnemy()
Coroutine runs through and exit afterwards.
You have to lock it in some loop, like this:
IEnumerator SpawnEnemy ()
{
while (true) // Keep checking
{
if(_uimanager.playerExists == true)
{
Vector3 position = new Vector3(Random.Range(-8.23f, 8.23f), 5.7f, 0.0f);
Instantiate(_enemyShipPrefab, position, Quaternion.identity);
yield return new WaitForSeconds (5.0f); // After spawning waits 5secs
}
yield return null; // Starts loop with next frame.
}
}
Upvotes: 4