Skip to content

Adding Enemies

John Nguyen edited this page Sep 4, 2020 · 3 revisions

Want to add your own enemy into the game? This page will show you how to do it!

Prerequisites: The game is properly set up on Unity. Not sure how to do this? Follow this link!


Creating a Prefab

  1. Select a Level from the Scenes folder. (For this tutorial I'm selecting Level2). Right-click on the file hierarchy on the left and Create Empty. Rename your GameObject into your enemy name.

  1. Add your enemy sprite to the Sprites folder, and drag and drop onto the GameObject from Step 1. (If you can't drag and drop your sprite into the GameObject, check your sprite in the Inspector tab. Make sure your texture type is "Sprite" and apply these changes).

*** IMPORTANT Click on your Sprite in the hierarchy and on the Inspector, click on Add Component. Add the DestroyPrefabOnExit.cs script. (Add this script to the GameObject with the SpriteRenderer)IMPORTANT ***

  1. Drag and drop the GameObject from the file hierarchy to the Prefab folder.

  1. Delete the GameObject from the file hierarchy. Open the object you dragged into the Prefab folder. Under the name of your prefab, change the tag to "Enemy".

Add three components to the Prefab

  • RigidBody2D

    • Set Body Type to Kinematic
  • 2D Box Collider

    • Resize the collider to your sprite
  • Animation

    • Click on Animation and add the EnemyDamageAnimation anim file

    • Uncheck Play Automatically

Animating the EnemyDamageAnimation

  1. Open Window -> Animation -> Animation. Click on Add Property.

Navigate: "Your Sprite Name" -> Sprite Renderer -> Color

  1. Move your timeline to the 0.15 second mark. On the left side, click the button that says Add Keyframe.

  1. Set the color (1, 0, 0, 1) at the 0.15 mark. (1, 1, 1, 1) anywhere else.

Coding your enemy script

  1. Go back to your Prefab and Add Component. Select New Script and create the script.

  1. Open your new C# on whatever text editor.

Have your class inherit from EnemyPlane instead of Monobehavior. Delete the Start() and Update() functions.

The EnemyPlane class has numerous functions and properties that you can manipulate and Override. Take advantage of Polymorphism!

Your script should look like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FW_190 : EnemyPlane
{

}
  1. For this tutorial my enemy will shoot bullets. Shooting any other projectile will follow the same pattern.

Add this as a property of your class. We will be using this property to Instantiate the EnemyBullet projectile in Unity.

public GameObject bulletPrefab
  1. Override the function InitializeEnemy(). This function executes when your enemy is Instantiated. Add code that initializes your enemy here. For this enemy, I am going to set it's velocity.
    public override void InitializeEnemy()
    {
        //The enemy will in a downwards direction
        this.rb.velocity = new Vector3(0, -1, 0) * speed;
    }
  1. Override the Attack() function. This function executes depending on the attackSpeed property of EnemyPlane.

Here, I want my enemy to attack in a random spread (like a shotgun) in the downwards direction. The most important thing you want to look out for in this tutorial when coding this section is inside the for loop.

    public override void Attack()
    {
        Vector3 pos = new Vector3(transform.position.x, transform.position.y - .65f, transform.position.z);

        //Shoot 5 - 8 bullets
        int numberOfBullets = Random.Range(5, 9);

        //shoot down
        float angle = (255.0f / 180.0f) * Mathf.PI;
        //shoot in spread of 30 degrees
        float angleOffset = (Mathf.PI / 6) / numberOfBullets;
        for (int i = 0; i < numberOfBullets + 1; i++)
        {
            //create the EnemyBullet GameObject at pos.
            GameObject go = Instantiate(bulletPrefab, pos, Quaternion.identity);

            //Get the EnemyBullet script from GameObject
            EnemyBullet bullet = go.GetComponent<EnemyBullet>();

            //Set the direction the bullet travels in
            bullet.targetVector = new Vector3(Mathf.Cos(angle), Mathf.Sin(angle), 0);

            //Set the speed of the bullet
            bullet.speed = 150;

            //Set the damage of the bullet
            bullet.damage = 10;

            angle += angleOffset;
        }
    }

The Finishing Touches

  1. Fix any compiling errors and navigate back to your Prefab on the Unity editor. In the Inspector you should see public variables in your script. Set these values:
  • Explosion Prefab (In the Prefab folder, this prefab will play an animation when your enemy dies)
  • Name (Name your enemy! This will display in the scoreboard at the end of a level)
  • Speed (How fast your enemy will travel across the screen)
  • Attack Speed (How often your enemy will execute the Attack() function)
  • Current Health (How much damage your enemy can take)
  • Points (How many points you award the player if they destroy your enemy) *** IMPORTANT Please make this in factors of 10. I can't guarantee your enemy will work or spawn if it isn't IMPORTANT ***
  • BulletPrefab (The projectile that MY enemy will be shooting in the Attack() function. Yours could be different depending on the projectile you choose).

  1. Exit the prefab editor and open up the Level you want to spawn your enemy in. Click on Game in the file hierarchy on the left.
  2. Add your enemy in Enemy Data. Modify the size of the array. Drag and drop your prefab from the Prefab folder into Prefab property. Input the amount of points your enemy is worth in the Cost property.

OPTIONAL 16. Spawn your enemy in a group. Open Enemy Squadron and add an element. Add an array in Planes and add the index of your enemy. Check staggered if you want to spawn your enemies consecutively.

In my case, I am spawning 3 of my enemies at the same time.

  1. Finally, check if your enemy works by pressing the play button at the top of the editor! If it doesn't work, Debug or check the FAQ section!

FAQ

  1. Q: My public variables aren't showing up in the inspector! WHY!

    A: Check if you have any compiler errors.

  2. My enemy isn't moving.

    A: Two possible issues. Either you didn't set rb.velocity in your script or the speed of your prefab is 0 in the inspector.

  3. Q: I want to make more complex movements for my enemy, how?

    A: Override the Move() function in your enemy script. Also be careful to Override the Update() function to make sure your enemy does what you need it to do.

  4. Q: My enemy isn't spawning.

    A: Check Step 14 - 16

  5. Q: My enemy isn't taking damage and missiles are not tracking it. A: Remember to set the tag of your prefab object to enemy.

Clone this wiki locally