9. Game #3: The Break-Up – Unity 3.x Game Development by Example

Chapter 9. Game #3: The Break-Up

We've been learning pieces of game development like Lego bricks. We've chugged along merrily on two tracks simultaneously, learning about what we need to build to have a complete game, and how we can use Unity to build those pieces.

The Break-Up will be a simple catch game. "Catch" is in a genre of what we now call "mini-games" often, they are games within games. Catch, like keep-up, has a very simple mechanic. The player controls a thing, (like a paddle, a character, a bucket, or a trampoline), usually at the bottom of the screen, and other things fall or move towards the player-controlled thing from the top of the screen. In a catch game, the player has to connect his controllable thing with the falling things (people jumping out of buildings, cherries falling from a tree, and so on) to catch or collide with them. A common feature upgrade is to add bad things that the player must avoid.

That's how the unskinned mechanic works. Of course, you can skin it in a million different ways. One of the earliest catch games I ever played was called Kaboom! on the Atari 2600. The player controlled a group of buckets, and had to catch bombs dropped by the Mad Bomber villain at the top of the screen.

The skin I've cooked up for The Break-Up puts you in the role of a guy who's been kicked out of his apartment by his girlfriend. Your most prized possessions are your beer steins of the world collection and your cartoon bomb collection, and your ex-girlfriend is throwing both of them out the window! The bombs, naturally, are lit. You have to catch the fragile beer steins and avoid the bombs.

That skin is clearly just a little West of nuts, but it shows how far you can go with the fictional wallpaper on a simple mechanic.

So what are we going to need? We should have some kind of backdrop to set the scene, some beer steins and bomb models, and a character. Ideally, that character should be animated. Oh and we should probably learn how to blow stuff up too, because blowing stuff up is awesome. In this chapter, let's learn:

  • How to set up animations from external models

  • How to create particle effects like explosions and sparks

  • How to use Prefabs to handle multiple copies of the same Game Object

  • How to write one script to control multiple objects

  • How to make things appear onscreen out of thin air

As before, the first thing you should do is start a new Unity project for this chapter, and call it The BreakUp. Be sure to include the Particles.unityPackage file from the list. Once your project starts up, save the default Scene and call it Game. Next, download and import the assets package for this chapter and all of the goodies you need to build the game will show up in the Project panel, in their own Materials and Models folders.

Note

Conversion perversion

As with the heart, hands and tray models from our Ticker Taker project, these particular goodies were created in Blender a free 3D modeling package. Then they were exported to the .fbx format, a common format among different 3D software packages. The drawback in converting your work to a common format is that certain things can be lost in translation faces can be flipped inside out, textures can show up in the wrong place or not at all, and the model might not look the way you want it to. Remember that Unity can handle a number of native 3D file formats. There are advantages and disadvantages to working with native file formats instead of common formats like .fbx, which you'll discover as you gain more experience with Unity.

Time for action – Bombs away!

Let's cut right to the chase here: big round cartoon bombs are great. Real-life bombs aren't quite as much fun, so let's keep it cartoony. We'll set up our cartoon bomb model and add a special effect called a Particle System to make it look as though the fuse is lit.

  1. In the Project panel, open the Models folder by clicking on the gray arrow to expand it.

  2. Drag the bomb model into the Scene view.

  3. In the Inspector panel, change the bomb's Transform Position values to 0, 0, 0 on the X, Y, and Z axes to place the bomb at the origin of your 3D world. You can also click on the gray gear icon and choose Reset Position from the dropdown.

  4. Hover your mouse over the Scene view and press the F key. This places focus on the bomb, which zooms into view.

  5. Click on GameObject | Create Other | Particle System.

  6. In the Inspector panel, change the X, Y, Z Position values of the Particle System to 0, 3, 0. This places the Particle System at the tip of the fuse.

  7. In the Hierarchy panel, rename the Particle Effect as Sparks.

Particle systems give games their zest. They can be used to depict smoke, fire, water, sparks, magic, jetstreams, plasma, and a pile of other natural and unnatural phenomena. Essentially, they're a ton of tiny little images that turn to face the camera, in a common 3D technique called billboarding. Each little picture can be textured, just like the Material on a 3D model. The little pictures support transparency, so they don't have to look like squares. Particle Systems have an emitter, which is where the particles come from. The built-in Particle System that ships with Unity lets you control a dizzying array of additional parameters, such as the number, color, frequency, direction, and randomness of the particles.

Note

In pursuit of shiny objects

Many game developers use particle effects as a cheap trick to reward their players. For many casual gamers, the best piece of feedback in a puzzle game is a satisfying sound effect paired with an explosion of particles. Games like Bejeweled and Peggle put particle systems to work with great results.

Right now, our Particle Effect looks like spooky forest fairy magic floating around our bomb. We want something closer to the classic Warner Bros. Wile E. Coyote bomb, with sparks shooting out of the fuse. Let's explore the wide range of settings that Unity's Particle Systems offer.

Click on the Sparks Particle System in the Hierarchy panel if it's not already selected.

Check out the Inspector panel. There are a metric ton of settings and dials for tweaking particle systems! We won't discuss them exhaustively because that's what software manuals are for. Suffice it to say, the best way to get what you want out of particle systems is to poke things until it looks right. Let's get poking!

Time for action – Poke those particles

  1. Adjust the dials on your Particle System to match these values:

    Ellipsoid Particle Emitter:

    • Emit: checked

    • Min Size: 0.5

    • Max Size: 0.5

    • Min Energy: 0.05

    • Max Energy: 0.1

    • Min Emission: 200

    • Max Emission: 200

      Keep all other settings in this section at their default.

Size makes sense that's the size of the little pictures. If you crank these settings up, you'll see big flat pictures, and the magic of particle systems will simultaneously make more sense, and will be completely ruined for you.

The energy settings govern how long it takes particles to die. We've cranked these dials way down to ensure that our particle lifespans are fast and frantic.

Emission settings govern how many little particle pictures will be spat out by the emitter. The emitter, if you haven't guessed, is an invisible ellipsoid from which the particles emanate.

Move down to the next section, the Particle Animator. Here, we can make the particles animated through a range of colors. We can also make the particles swirl and bend, but as sparks don't really swirl or bend, we'll leave those settings alone. With something fast and frenetic like a bunch of sparks, we can choose a bunch of hot colors to give the particles a sparky kind of look. Click on each color swatch next to the Color Animation[x] labels and cook up some hot, sparky colors. Here are the values I used:

Color Animation[0]: 255 / 255/ 255 (white)

Color Animation[1]: 255 / 0/ 0/ (red)

Color Animation[2]: 255 / 255/ 0 (yellow)

Color Animation[3]: 126 / 0 / 0 (dark red)

Color Animation[4]: 255 / 190 / 0 (orange)

Great! That's looking more sparky already!

The last slider on the bottom of the color widget is labeled A, which stands for "Are we gonna be able to see through this color or not?" (It could also stand for "Alpha", which means roughly the same thing.)

Notice that there's a black and white indicator beneath each color swatch in the Particle Animator. This strip reflects the Alpha value of the color.

You can play around with the Alpha slider to your heart's content, adjusting the transparency of each color as you see fit.

Time for action – Creating a spark material

In order to really pull off this effect, we should add a material to the Particle System. We need to create that material first, so let's turn our attention to that for the moment.

  1. Create a new Material by either right-clicking/secondary-clicking in the Project panel and choosing Create | Material, or by clicking on Assets | Create | Material in the menu.

  2. Name the new Material as Spark. The sphere icon helps us remember that this is a Material. Consider dragging this new Material into the Materials folder to keep your project organized.

  3. In the Inspector panel, choose Particles | Additive as the Shader type.

  4. Click on the Select button in the square swatch labeled Particle Texture (it should say None (Texture 2D) inside the square), and choose the texture labeled fire4 from the list. If you don't see it in the list, you may have forgotten to import the Particles assets package when you started your project. To rectify this, set your computer on fire, then go outside and enjoy the fresh air and sunshine.

  5. (Or if you're bound and determined to continue, import the Particles package under Assets | Import Package.)

  6. In the Hierarchy panel, click again to select your Sparks Particle System.

  7. In the Inspector panel, uncheck Cast Shadows and Receive Shadows in the Particle Renderer section. We're not exactly going for a realistic look here, so we can spare Unity the chore of rendering fancy shadow effects that no one will notice. (Note that shadow casting is a Unity Pro feature. If you're not running Unity Pro, fuhgeddaboudit!)

  8. Still in the Particle Renderer section in the Inspector panel, expand the Materials section by clicking on the gray arrow.

  9. In the pop-up labeled Element 0, change the Default-Particle material to your newly created Spark Material.

There! Now it's looking even more sparky!

Have a go hero Time to ignite your creative spark

Do you like fiddling with buttons and knobs? Maybe your eyes lit up when you saw all the gory bits in Unity's Particle System? This is a great time to put the book down and fiddle to your heart's content (with Unity that is). Maybe you can find some settings that make the sparks look even more sparky? You might try drawing your own texture that makes the sparks look sharper or pointier than the comparatively smooth and fluffy fire texture we're using. Or better yet, perhaps you could create another particle system and make a thin trail of gray smoke to flow up from your fuse? Check out the velocity settings, which give your particles direction, if you want to pull this off.

You can find a detailed explanation of every little Particle System setting in the Unity User Guide at this address: http://unity3d.com/support/documentation/Manual/Particle Systems.html.

Time for action – Prefabulous

Our game is going to contain not one bomb, but many. As with programming, doing something more than once in Unity completely stinks, so we're going to take a shortcut. We're going to create a built-in thing called a Prefab that will let us create a reusable bomb, much the same way we created a programmatic function that we could call multiple times in our script.

Follow these steps to create your first Prefab:

  1. Right-click/secondary-click on the Project panel and choose Create | Prefab, or click on Assets | Create | Prefab in the menu. A gray box icon appears in your Project panel, labeled new prefab. Because the box is gray, we know this Prefab is empty.

  2. Rename the Prefab as Bomb. Just like the Spark Material, the icon helps us keep track of what type of thing it is. For further clarity, consider adding the Bomb Prefab to a new folder, which you should call Prefabs.

  3. In the Hierarchy panel, click-and-drag the Sparks Particle System to the Bomb Game Object. You'll see that warning about losing the prefab that's okay. Click on Continue.

  4. In the Hierarchy panel, click on the gray arrow next to the bomb model parent, and you'll see the Bomb model and the Sparks Particle System nestled safely inside.

  5. In the Hierarchy panel, click-and-drag the parent Bomb Game Object label, the one that the Bomb model and the Sparks Particle System are nestled beneath, onto the Bomb Prefab in the Project panel (remember, it has an empty gray cube icon next to it).

When you pull the Bomb Game Object into the empty Prefab the gray Prefab icon lights up blue. Filled Prefabs are blue, while empty Prefabs are gray. And 3D model icons look suspiciously like filled Prefab icons, except that they have a little white page on their blue boxes.

What just happened what's a Prefab?

So what the heck is a Prefab, anyway? It's a container that holds stuff, and it's magically reusable. Now that the Sparks and the Bomb are stowed safely inside a Prefab, we can populate the Scene with a whole pile of bombs. If you make any changes to the Prefab, all other instances of the Prefab receive the same change. Let's see this in action:

  1. Click on the Bomb parent in the Hierarchy and press the Delete key on your keyboard (Command + Delete on a Mac) to get rid of it. It's okay. The Bomb model and the Sparks are tucked inside our new Prefab down in the Project panel.

  2. Click-and-drag the Bomb Prefab out from the Project panel into the Scene lots of times. Populate your Scene with five or more Bomb Prefabs.

  3. Move the Bombs around the Scene so that they're not all stacked on top of each other.

  4. In the Inspector panel, open up the Bomb Prefab by clicking on its gray arrow.

  5. Click on the Sparks Particle System inside the Bomb Prefab.

  6. In the Inspector panel, scroll down to the Particle Renderer section.

  7. Click on the Particle Texture swatch, where we originally chose the fire4 texture, and choose a different texture from the list. Choose something silly, like the soapbubble texture.

  8. All of the Bomb Prefabs in your Scene should update to display a soapbubble texture on their particle systems! Test your game to see this in action.

  9. Be sure to change the texture back to fire4 before continuing.

You've just proven that what happens to the master prefab happens to all prefabs. We'll come back to the bombs in a bit. For now, delete all of the Bomb Prefab instances from the Hierarchy panel to get back to an empty Scene.

Note

Flashback

If you've ever used Flash, the concept of Prefabs may feel familiar. Prefabs behave very much like Flash Movieclips.

Time for action – Lights, camera, apartment

One of the models in the Models folder in the Project panel is called brownstone. This is the brownstone apartment building from which our hapless hero has been ejected. Let's set it up:

  1. In the Project panel, click on the gray arrow to expand the Models folder.

  2. Click-and-drag the brownstone model into the Scene.

  3. In the Inspector panel, set the apartment building's Transform Position to X:0, Y:0, Z:0.

    Our camera's not exactly pointed the right way. Let's adjust the camera's Transform to get a nice low-angle view of the brownstone building.

  4. Click to select the Main Camera in the Hierarchy panel.

  5. In the Inspector panel, change its Transform Position to 35, 2.5, -38.

  6. Change its Rotation values to 333, 355, 0.4.

    • The brownstone should swing into view in your Game view.

      Change the camera's field of view to 51, to hide the fact that the brownstone model is only two floors high. This place is rather dimly lit, so let's set up a light in our scene to simulate daytime.

  7. Navigate to GameObject | Create Other | Directional Light.

  8. In the Inspector panel, change the light's Rotation values to X:45, Y:25, Z:0.

Now the building is illuminated rather nicely.

Time for action – Adding the character

The biggest missing piece at this point is the player character. Let's get him in the Scene.

  1. Create an empty Prefab and name it Character. (Drop it into the Prefabs folder if you'd like to keep your project organized.)

  2. In the Project panel, click and drag the character model from the Models folder into the Character Prefab.

  3. Click-and-drag an instance of the Character Prefab from the Project panel into the Scene.

  4. Use these settings to place the character:

    • Position: 24, 0, -16

    • Rotation: 0, 90, 0

These settings place the character at the foot of the brownstone. He looks like he's about to do some intensive aerobics with his arms out like that. This is called the "Christ pose" or the "T-pose", and it's the preferred position for a character model because it makes it easier to add a skeleton to the mesh, a process called rigging. A fully-rigged character is called a character rig.

Time for action – Registering the animations

The character model that we're using has been pre-animated in Blender. It has three animations: idle, step, and catch. Before we can play these animations using a Script, we have to tell Unity the frame ranges the model uses.

  1. In the Project panel, click on the character model inside the Models folder.

  2. In the Inspector panel, scroll down to the Animations section.

  3. Make sure that Bake Animations and Split Animations are both checked.

  4. Click on the little plus icon at the right edge of the box three times to add three new animations.

  5. Name the animations step, idle, and catch.

  6. Use these settings for the Start, End, and WrapMode parameters:

    • step 1-12, Loop

    • idle 22-47, Loop

    • catch 12-20, Once

  7. When you are finished, click on the Apply button.

Now that these animations have been named and identified, we can call them up with code.

Time for action – Scripting the character

Let's do exactly that! We'll create a new Script, and use what we already know about following the mouse to snap the player character to our mouse movement. Then we'll tell the character which animation cycle to use when he's moving around.

  1. Create a new JavaScript Script. Rename it Character. If you're keeping your project tidy, consider creating a new folder called Scripts and dropping your new script into it.

  2. Open the script and type in this code:

    var lastX:float; // this will store the last position of the //  character
    var isMoving:boolean = false; //flags whether or not the player is //   in motion
    function Start() 
    {
       animation.Stop();  // this stops Unity from playing the 
       character's default animation.
    } 
    
    function Update()
    {
       var halfW:float = Screen.width / 2;
       transform.position.x = (Input.mousePosition.x)/20;
    }
    

    So far, this should all look very familiar. We're using the same type of commands we used with the keep-up game to make the Game Object follow the mouse around, but this time the player is locked to the X-axis, so he'll only be able to move from side to side.

    Now we'll add a chunk of logic in the Update function to determine whether or not the player is moving.

  3. Add the following code to your Update function:

    function Update()
    {
      var halfW:float = Screen.width / 2;
      transform.position.x = (Input.mousePosition.x)/20;
      if(lastX != transform.position.x)
      {
        // x values between this Update cycle and the last one
        // aren't the same! That means the player is moving the
    	//  mouse.
        if(!isMoving)
        {
          // the player was standing still.
          // Let's flag him to "isMoving"
          isMoving = true;
          animation.Play("step");
         } 
      } 
      else
      {
        // The player's x position is the same this Update cycle
        // as it was the last! The player has stopped moving the
    	// mouse.   
        if(isMoving)
        {
          // The player has stopped moving, so let's update the 
          // flag
          isMoving = false;
          animation.Play("idle");
        }
      }
      lastX = transform.position.x;
    }
    
  4. Save the script. Now attach the script to your Character Prefab in the Project panel. I find it tricky to master the click-and-drag process when it comes to Prefabs. Unity always thinks I'm trying to drag my script above or below the Prefab. For a sure-fire way to stick that script to your character, click on the Character Prefab in the Project panel. Then, in the menu, click on Component | Scripts | Character. You should see the Character script get added as a component in the Inspector panel.

  5. Play your game to try it out. When you move the mouse, the character loops through his "step" animation. When you stop moving the mouse, he goes back to his "idle" animation, looking for more stuff to catch.

What just happened stepping through the "step" code

The comments should help clarify this code. This crucial line:

if(lastX != transform.position.x)

means "if the last x position of the character does not equal the character's current x position..."we base the rest of the logic on that check.

If he was moving and he just stopped, flag him as "not moving" and play the "idle" animation. If he was not moving and he just started moving since the last Update cycle, flag him as "moving" and play the "step" animation.

Note

Why the flag?

We use the isMoving flag to determine that the player has just started or stopped moving since the last cycle. It's important that we play the "step" and "idle" animations only at a single point. If we were to issue the animation.Play command on every Update, the character would get stuck on the first frame of the animation. The animation would keep saying, "Play? Okay! Here's frame 1!" And then, a millisecond later, "Play? Okay! Here's frame 1!"

Time for action – Opening the pod bay door, Hal

I don't know about you, but I'm about ready to drop some bombs on this chump. We could do what we've done before and add a Rigidbody Collider Component to the bomb, as we did with the ball/heart in the keep-up game, and let Unity's physics take care of the rest. But in this case, we might like a little more control over the velocity of the bombs. So let's add Rigidbody and Collider Components to the bomb, but exclude it from Unity's gravity calculations.

  1. In the Project panel, click on the Bomb Prefab.

  2. Click on Component | Physics | Rigidbody. You should see the new Rigidbody Component appear in the Inspector panel.

  3. In the Inspector panel, uncheck the Use Gravity checkbox. This will exempt the bomb from Unity's gravitational pull. PROTIP: I kind of wish I had this checkbox on my own body. That would be fun.

  4. Click Component | Physics | Sphere Collider. We don't need any fancy poly-perfect Mesh Collider in this case because the bomb is basically a sphere anyway.

  5. In the Inspector panel, enter a value of 2 for the radius of Sphere Collider. That should fit the bomb snugly. You can confirm this by placing a Bomb Prefab in your Scene and checking it out, or you can take my word for it.

You'll remember from the keep-up game that the Rigidbody and Sphere Collider or Capsule Collider Components work together to make Game Objects collide with each other.

Time for action – Collision-enable the character

Now that the bomb is all rigged up, we'll be able to determine through code when it hits the player character. However, the player character is missing its Collider Component too! Let's fix that.

  1. Click to select the Character Prefab in the Hierarchy panel.

  2. Click Component | Physics | Box Collider in the menu. You'll see that "Losing prefab" warning. Don't fret just click on Add.

  3. In the Inspector panel, update the Size and Center settings for your new Box Collider with these values:

    • Center: -1, 8, 1

    • Size: 5, 16, 10

Just like we did with the bomb, we'll forego using a computationally complex Mesh Collider in favor of a rough-hewn primitive. We've made a big, ugly green box around the character. This will make less work for Unity, and for our game's purposes, anything fancier would be overkill.

Time for action – Re-prefab the prefab

Because we broke the Prefab by adding something new to it, any new instance of the Character Prefab we drag out of the Project panel won't have the Box Collider on it. We can tell Unity that we want this aberrant, and modify Prefab to actually overwrite what's in the Prefab container by clicking on the Apply button. Here's how to find it:

  1. Make sure the Character Prefab is selected in the Hierarchy panel.

  2. At the top of the Inspector panel, just beneath the Tag and Layer buttons, look for a set of three buttons that say Select, Revert, and Apply.

  3. Click on the Apply button. Go on. You know you want to.

When you apply the changes you made to your broken Prefab, it lights up blue again in the Hierarchy panel. This means that the Prefab in the Project panel has been updated to include these new changes. Now, every new Character Prefab you place in your Scene will have that Box Collider around it.

Note

Select and Revert

Wondering what those other two buttons are about? Click on Select, and Unity will highlight the source Prefab. That way you can make changes to it (and all its instances) without going through this change/break/apply process.

The Revert button will hook your broken Prefab back up to the source Prefab, discarding any changes you've made to it.

Time for action – Apocalypse now?

Enough prattle. It's bomb time!

  1. Create a new JavaScript and name it Bomb. Drop it in the Scripts folder if you're keeping things tidy.

  2. Open up the script and type the following code:

    function Update()
    {
      transform.position.y -= 50 * Time.deltaTime;
      if(transform.position.y < 0)
      {
        transform.position.y = 50;
        transform.position.x = Random.Range(0,60);
        transform.position.z = -16;
      }
    }
    

We've seen these keywords before, so there should be no surprises here. On every update cycle, move the bomb down in the Y-axis by 50 units per second:

transform.position.y -= 50 * Time.deltaTime;

If the bomb has fallen through the floor:

if(transform.position.y < 0) {

Pop the bomb back up to the top of the apartment building:

transform.position.y = 50;

And use Random.Range to make it appear in a different spot along the top of the building. This will create the illusion that there are multiple bombs falling from the sky.

Save this script. Just as we did with the Character Prefab, click on the Bomb Prefab in the Project panel and select Component | Scripts | Bomb Script to add the new script to the bomb.

Drag the Bomb Prefab into your Scene, and give it the following Transform Position: x:-9, y:36, z:-16. Now playtest your game.

Zut alors! There are sparky, lit bombs falling from the top of that apartment building! For added amusement, try catching one on your character's face. We haven't done any collision handling yet, so our ousted friend gets a grill full of bomb.

Time for action – Go boom

I must say, there's a distinct missing element to our bomb-centric game to this point. What could it be, what could it be? Ah, yes. ASSPLOSIONS. When they hit the ground OR the player, those bombs need to blow up real good. Sounds like a particle system would do just the trick.

  1. Make sure you're no longer testing the game.

  2. Click on GameObject | Create Other | Particle System. Rename it Explosion.

  3. Create a new Prefab and name it Explosion. (Or Assplosion if you want to be awesome about it.) Drop it into your Prefabs folder to keep the project organized.

  4. From the Hierarchy panel, click-and-drag the Explosion Particle System into the Explosion Prefab container.

  5. Re-select the Explosion Game Object in the Hierarchy panel. Point your mouse at the Scene, and press the F key to bring the new Particle System into focus.

  6. In the Inspector panel, adjust the Explosion's settings thusly:

    • Emit: checked

    • Min Size: 5

    • Max Size: 5

    • Min Energy: 1

    • Max Energy: 1

    • Min Emission: 150

    • Max Emission: 150

    • World Velocity: 0, 10, 0 (This will make the particles shoot upward along the Y-axis.)

    • Local Velocity: 0, 0, 0 (Leave it at the default.)

    • Rnd Velocity: 10, 10, 10 (Crazy random particle scattering!)

    • Emitter velocity scale: 0.05 (Leave it at the default.)

  7. Leave everything else in this section at its default value, EXCEPT the One Shot checkbox. This is vital and should be checked. A One Shot particle system gives us single splashes, splurts, and explosions.

  8. In the Particle Animator section, choose a series of colors. I used the same values as the Spark system, except I flipped the orange and dark red colors to fool myself into thinking I was doing something new and exciting.

    • Color Animation[0]: 255 / 255/ 255 (white)

    • Color Animation[1]: 255 / 0/ 0/ (red)

    • Color Animation[2]: 255 / 255/ 0 (yellow)

    • Color Animation[3]: 255 / 190 / 0 (orange)

    • Color Animation[4]: 126 / 0 / 0 (dark red)

      You'll find another important checkbox at the bottom of this section: it's called Autodestruct, and it should be checked. This means that once the particle system is finished blowing its wad, Unity will remove it from the scene.

  9. In the Particle Renderer section, uncheck Cast Shadows and Receive Shadows.

    (These matter only for Unity Pro users.) In the Materials pop up, choose the Spark Material that we used for our bomb fuse.

  10. If you move the Explosion around, you'll see from the Scene view that this explosion is entirely too large for the screen, as it flowers violently up over the character's head. Yes, it will do nicely.

  11. Change the Transform position of Explosion back to X:0 Y:0 Z:0, and click on the Apply button to commit these changes to the source Prefab.

Time for action – The point of impact

We're finished tweaking the explosion, so you should delete the instance of the Explosion Prefab from the Scene view. The original stays safe and sound in the Prefab container in your Project panel. Naturally, we want this explosion to appear whenever we detect that the bomb has hit the ground. We've already put the logic in place to detect a ground hit remember that we're moving the bomb back up into the sky as soon as it drops below ground level. So it should be a reasonable hop, skip, and jump towards making that explosion happen. And luckily, it is!

  1. Open up your Bomb Script and add the following variable at the very top:

    var prefab:GameObject;
    
  2. Then, just after the code where we detect a ground hit, add this line:

    If(transform.position.y < 0)
    {
       Instantiate(prefab, transform.position, Quaternion.identity);
    

We created a variable called prefab at the top of the script to store some sort of GameObject. Note that small-p "prefab" is not a Unity keyword we're calling it that because calling it "monkeybutt" would make the code even more confusing.

The Instantiate command does exactly what you suspect it does. We need to pass it a reference to a Game Object (in our case, we've got one stored in the prefab variable), along with arguments to determine the position and the rotation of the thing. Then Unity goes looking for the Game Object we specified, and places it in the game.

What do we pass for the position value? The bomb's own position, before we move the bomb to the top of the apartment building. And what do we pass in for its rotation? SCARY MATH! BLAH!!

Once again, I'm not even going to pretend that I understand quaternion mathematics. What I do know is that Quaternion.identity means "no rotation" the object is aligned perfectly with the world or parent axes.

Time for action – Hook up the explosion

"But wait," you say. "How do we actually tell the Script what we want to instantiate?" Ah, there's the magic of Unity yet again. Save the Bomb Script, and follow these next steps:

  1. In the Project panel, select the Bomb Prefab.

  2. In the Inspector panel, find the Bomb (Script) Component. Notice that the variable we called prefab is listed there. (If you actually did call your variable "monkeyButt", you'll see that instead.)

  3. Click-and-drag the Explosion Prefab from the Project panel into the Prefab variable slot in the Inspector panel. You should see a little red, green and blue icon appear in the slot, with the label Explosion Prefab. I've got a good feeling about this!

Test out your game. The bomb falls from the top of the building, "hits" the ground, and calls in the Explosion Prefab before popping back up to the top of the building at some random X position. The Explosion, because it's set to Autodestruct, does its thing and then disappears from the scene. It's... *sniff*... it's a beautiful thing.

Summary

So! Do we have a game yet? Not quite. Catching a bomb with your face sounds like a great party trick, but our game is obviously missing a few things to make it playable. We still need to handle the collision of the bomb against the player, and we need to get those beer steins in there. They're apparently worth breaking up with your girlfriend, so they sound pretty important.

In the next chapter, we'll do all these things and more. Buckle your seatbelt and turn that page!