- Home /
Question by
kuos · Sep 04, 2016 at 07:01 AM ·
spawninginstantiate prefab
Spawning Enemies after a Player reaches a certain score
What I have: Predefined (empty game object) spawn points laid out across the top of the playable area Prefab Enemies to be spawned with a y velocity to go downwards upon spawning
What I want to do: * When the player reaches a score e.g. 10 points, start spawning the new type of enemies.
The issue: Enemies aren't spawning as I expected and I see the print statement in the Update function execute(print ("spawning Top Enemies Now!");) but I don't see the console logging "hello higher world" so my SpawnTop function isn't working out for me.
Anything obviously wrong?
using UnityEngine;
using System.Collections;
public class TopEnemySpawnScript : MonoBehaviour {
public GameObject enemy; // The enemy prefab to be spawned.
public Transform[] spawnPoints; // An array of the spawn points this enemy can spawn from.
private ScoreTrackScript ScoreTrackScript;
private bool topSpawnThreshold = false;
void Start ()
{
StartCoroutine("SpawnRoutine"); //Starting a coroutine to be able to wait for specified time
ScoreTrackScript = GameObject.Find ("ScoreTracker").GetComponent<ScoreTrackScript>();
}
void Update()
{
if (ScoreTrackScript.getScore () == 2) {
topSpawnThreshold = true;
print ("spawning Top Enemies Now!");
}
}
IEnumerator SpawnRoutine()
{
yield return new WaitForSeconds(2);
while (topSpawnThreshold) {
SpawnTop ();
}
}
void SpawnTop() //Spawns Top Enemies from above the screen after player meets a score threshold
{
int spawnPointIndex = Random.Range (0, spawnPoints.Length);
Instantiate (enemy, spawnPoints [spawnPointIndex].position, spawnPoints [spawnPointIndex].rotation);
print ("hello higher world");
}
}
Comment
Best Answer
Answer by doublemax · Sep 04, 2016 at 07:39 AM
At the beginning topSpawnThreshold is false, so the Coroutine will just exit. You probably want something like this:
IEnumerator SpawnRoutine()
{
while(true)
{
if( topSpawnThreshold) {
SpawnTop ();
}
yield return new WaitForSeconds(2);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612092140im_/https://answers.unity.com/themes/thub/images/avi.jpg)