Unity 2020 By Example
上QQ阅读APP看书,第一时间看更新

Spawning enemies

To make the level fun and challenging, we'll need more than simply one enemy. In fact, for a game that's essentially endless, we'll need to add enemies continually and gradually over time. Essentially, we'll need either regular or intermittent spawning of enemies, and this section will add that functionality. Before we can do this, however, we'll need to make a prefab from the enemy object. The steps are the same as for previously created prefabs: select the enemy in the Hierarchy panel and then drag and drop it to the Project panel in the Prefabs folder:

Figure 3.28 – Creating an enemy prefab

Figure 3.28 – Creating an enemy prefab

Now, we'll make a new script, called Spawner.cs, that spawns new enemies in the scene over time within a specified radius from the player spaceship. This script should be attached to a new, empty GameObject in the scene:

public class Spawner : MonoBehaviour

{

    public float MaxRadius = 1f;

    public float Interval = 5f;

    public GameObject ObjToSpawn = null;

    private Transform Origin = null;

    void Awake()

    {

         Origin = GameObject.FindGameObjectWithTag           ("Player").transform;

    }

    void Start ()

    {

         InvokeRepeating("Spawn", 0f, Interval);

    }

    void Spawn ()

    {

         if(Origin == null)         {               return;

         }

         Vector3 SpawnPos = Origin.position + Random.              onUnitSphere * MaxRadius;

         SpawnPos = new Vector3(SpawnPos.x, 0f, SpawnPos.z);            Instantiate(ObjToSpawn, SpawnPos, Quaternion.           identity);

    }

}

During the Start event, the InvokeRepeating function will spawn instances of ObjToSpawn (a prefab) repeatedly at the specified Interval, measured in seconds. The generated objects will be placed within a random radius from a center point, Origin.

The Spawner class is a global behavior that applies scene-wide. It does not depend on the player, nor any specific enemy. For this reason, it should be attached to an empty GameObject. Create one of these by selecting GameObject | Create Empty from the application menu. Name the new object something memorable, such as Spawner, and attach the Spawner script to it.

Once added to the scene, from the Inspector, drag and drop the Enemy prefab to the Obj To Spawn field in the Spawner component. Set the Interval to 2 seconds and increase the Max Radius to 5, as shown in Figure 3.29:

Figure 3.29 – Configuring Spawner for enemy objects

Figure 3.29 – Configuring Spawner for enemy objects

Now (drum roll), let's try the level. Press Play on the toolbar and take the game for a test run:

Figure 3.30 – Spawned enemy objects moving toward the player

Figure 3.30 – Spawned enemy objects moving toward the player

You should now have a level with a fully controllable player character surrounded by a growing army of tracking enemy ships! Excellent work!