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

Creating the explosive particle system

In this twin-stick shooter game, both the player and enemies are spaceships. Therefore, a suitable particle effect for their destruction would be an explosive fiery ball. To achieve explosions, we can use a particle system. This refers to a special kind of object that features two main parts, namely, a Hose (or Emitter) and Particles. The emitter spawns or generates new particles into the world, and the particles are many small objects or pieces that, once spawned, move and travel along a trajectory. Particle systems are ideal for creating rain, snow, fog, sparkles, or, in our case, explosions!

With that in mind, let's select and customize a particle system for our game.

Selecting the particle system

We can create our own particle systems from scratch using the menu option GameObject | Particle System, or we can use any pre-made particle system included with Unity. In this game, we'll use some of the premade particle systems. To do this, perform the following steps:

  1. First import the Unity Standard Assets package. I won't go into detail how to do this here as it was covered in Chapter 1, Exploring the Fundamentals of Unity, so please refer back to that chapter for a step-by-step guide.
  2. Once the Standard Asset Package has been imported, the particle systems will be added to the Project panel in the Standard Assets | ParticleSystems | Prefabs folder:

    Figure 3.18 – Particle systems imported to the Project panel

    Tip

    Note that the preview for a particle system is only played in the Scene view while it is selected in Hierarchy.

  3. You will observe from Figure 3.18 that an explosion system is included among the default assets. To make sure it is fit for our purposes, you can test it by dragging and dropping the explosion to the scene and pressing play on the toolbar to see the explosion in action, as shown in Figure 3.19.

Great! We're almost done, but there's still a bit more work to do. We've now seen that an appropriate particle system is available, and we could drag and drop this system to the Death Particles Prefab slot in the Health component in the Inspector. This will work technically: when a player or enemy dies, the explosion system will be spawned, creating an explosion effect. However, the particle system will never be destroyed! This is problematic because, with every enemy death, a new particle system will be spawned. This raises the possibility that, after many deaths, the scene will be full of disused particle systems. We don't want this; it's bad for performance and memory usage to have a scene full of unused objects lingering around. To fix this, we'll modify the explosion system slightly, creating an altered prefab that will suit our needs. In future, we'll look at more advanced object management techniques, such as object pooling, but now we will simply destroy the objects after a specified time.

Customizing the particle system

To begin altering the particle system, drag and drop the existing explosion prefab anywhere to the scene and position it at the world origin, as shown in Figure 3.19:

Figure 3.19 – Adding an explosion system to the scene for modification

Next, we must refine the particle system to destroy itself soon after instantiation. To accomplish this, we'll create a new C# script called TimedDestroy.cs:

public class TimedDestroy : MonoBehaviour

{

    public float DestroyTime = 2f;

    void Start ()

    {

         Destroy(gameObject, DestroyTime);

    }

}

The TimedDestroy class destroys the object to which it's attached after a specified interval (DestroyTime) has elapsed. The script is simple: in the Start function, a call to Destroy is made, passing the script's gameObject and the desired DestroyTime. This call holds no surprises and will destroy the object after the desired amount of time has passed.

Tip

You can also destroy a particle system on completion by setting Stop Action to Destroy in the Inspector. This setting will destroy the particle system without the need to write a single line of code. However, this is not entirely suitable for our explosion particle, as it actually consists of several particle systems that are all children of a parent object. We could have set Stop Action for each particle system individually, but this would not have destroyed the parent object. These parent objects would accumulate over time, thereby reducing the performance of our game.

Drag and drop the TimedDestroy script to the explosion particle system in the scene and then press Play on the toolbar to test that the code works and that the object is destroyed after the specified interval. Remember that, as DestroyTime is a public variable, it can be adjusted in the Inspector.

The TimedDestroy script should remove the explosion particle system after the delay expires. So, let's create a new and separate prefab from this modified version. To do this, perform the following steps:

  1. Rename the explosion system in the Hierarchy panel to ExplosionDestroy.
  2. Drag and drop the system from Hierarchy to the Project panel in the Prefabs folder. Unity will automatically create a new prefab, representing the modified particle system.
  3. Now, drag and drop the newly created prefab from the Project panel to the Death Particles Prefab slot on the Health component for the player in the Inspector. Setting this field means that the prefab is instantiated when the player dies:

Figure 3.20 – Configuring the health script

If you run the game now, you'll see that you cannot initiate a player death event to test the particle system generation. Nothing exists in the scene to destroy or damage the player, and if you set the Health points to 0 in the Inspector, it doesn't use the C# property set function. For now, however, we can write temporary code that triggers an instant kill when the spacebar is pressed. Refer to Code Sample 3.7 for the modified health script:

public class Health : MonoBehaviour

{

    void Update()

    {

        if(Input.GetKeyDown(KeyCode.Space))

        {

            HealthPoints = 0;

        }

    }

}

Run the game now and press the Spacebar to trigger an instant player death. You should see the player object removed from the game and the particle system generated until the timer destroys that too.

Excellent work! We now have a playable, controllable player character that supports health and death functionality. We'll introduce enemies to the game next.