Now that we have all of the pieces together, let's make it so that we will only spawn a few ducks at a time and have a few of them appear at a time.
TargetBehaviour
script, and in the Start
function, remove the following line:ShowTarget();
This will keep the targets in their original position until we are ready for them to be shown.
GameController
by going to the Project tab and then selecting Create | C# Script and once it appears give it a name of GameController
. Double-click on the file to open up your IDE of choice and add the following code:using UnityEngine; using System.Collections; // IEnumerator using System.Collections.Generic; // List public class GameController : MonoBehaviour { public static GameController _instance; [HideInInspector] // Hides var below from inspector public List<TargetBehaviour> targets = new List<TargetBehaviour>(); void Awake() { _instance = this; } // Use this for initialization void Start () { StartCoroutine("SpawnTargets"); } void SpawnTarget() { // Get a random target int index = Random.Range(0, targets.Count); TargetBehaviour target = targets[index]; // Show it target.ShowTarget(); } IEnumerator SpawnTargets() { yield return new WaitForSeconds(1.0f); // Continue forever while (true) { int numOfTargets = Random.Range(1, 4); for (int i = 0; i < numOfTargets; i++) { SpawnTarget(); } yield return new WaitForSeconds(Random.Range(0.5f *numOfTargets, 2.5f)); } } }
TargetBehaviour
script and add the following function:// Called before Start void Awake() { GameController._instance.targets.Add(this); }
0
, 0
, 0
, and rename it GameController. Afterwards, add a GameController component to it.Now as you can see the ducks appear in waves with a random number of ducks appearing after a period of time. Excellent!