Creating waves of targets

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.

  1. Open up the 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.

  2. Next, we will create a new script named 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));
            }
        }
    }
  3. Next, we need to fill the values of targets, so to do that, go back into the TargetBehaviour script and add the following function:
        // Called before Start
        void Awake()
        {
            GameController._instance.targets.Add(this);
        }
  4. Then, add an empty game object to the scene (GameObject | Create Empty), center it at 0, 0, 0, and rename it GameController. Afterwards, add a GameController component to it.
  5. Save your project and run the game:
    Creating waves of targets

Now as you can see the ducks appear in waves with a random number of ducks appearing after a period of time. Excellent!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset