Unity Beginner to Hero Part 10: Damaging Enemies

Lesson 10. A milestone. Gone are the days when words like Vector3 or World-Space were confusing and meaningless to you. You have passed beyond your neophyte days. Greatness is within grasp.

Alright this is wordpress not FictionPress. On with the tutorial. This time around, we’re going to create a new script that will allow objects to be damaged and destroyed by the rockets we created in the previous lessons. Let’s begin by creating a new script, calling it “EnemyHealth.” Since I think we’re getting quite advanced over here, I’m not going to paste the script piecemeal—I don’t think we need to go over public fields for the third (fourth?) time.

using UnityEngine;
using System.Collections;

public class EnemyHealth : MonoBehaviour {

    public float initialHealth = 10.0f;

    private float currentHealth;

    void Start () {
        currentHealth = initialHealth;
    }

    public void TakeDamage(float damage)
    {
        currentHealth -= damage;

        if (currentHealth < 0)
        {
            Destroy(gameObject);
        }
    }
}

We have the usual crop of fields, which we initialize in the Start method, another of the special methods that are part of all Unity components. Start is called once and only once for each component, when it is enabled. If the script is never enabled, Start is never called.

We’ve added a new method named TakeDamage, this time with the public access modifier in front of it. Despite never having stated it explicitly, all of our previous methods have been private—fields and methods are private by default in C#.

TakeDamage is fairly simple in concept and execution. A single float variable is passed into the method that decrements the current amount of health the enemy has. Once it is below zero, the enemy is destroyed.

This script is finished, but we’re not quite—we need to make it so that the rockets call TakeDamage on enemies they collide with. Back in the Rocket script, add a new public float field named damageDealt. In the OnTriggerEnter method, add the following lines at the top.

EnemyHealth health = col.gameObject.GetComponent<EnemyHealth>();

if (health != null)
{
	health.TakeDamage(damageDealt);
}

We’re using GetComponent again, but this time it’s to grab one of the components we built ourselves! We store the component in the health variable, and then check to see if it’s null or not—GetComponent returns null if there is no such component attached to the object, since not all objects the rocket will collide with (walls, ground, ceiling) are enemies and can be damaged. Last but not least, we call the TakeDamage method and pass in damageDealt as an argument. We are able to call this method on health as we gave the method the public access modifier.

Back in the editor, add the EnemyHealth script to a few of the boxes we dropped into the level. You should be able to play the game now and destroy them with a few rockets!

ds

I added particle effects for some personality. Definitely a topic that would be fun to cover in a future lesson!

Before concluding the first set of these tutorials, let’s add one more thing. By now you’ve probably noticed that it can be somewhat annoying to play a shooter game with the mouse wandering all over the screen. In most shooters, and many other kinds of games, the mouse is hidden from view and locked to the center of the screen. Let’s do this now. Create a new script and name it “MouseLock.” Add the following lines in the Update method.

if (Input.GetButtonDown("Fire1"))
{
	Cursor.lockState = CursorLockMode.Locked;
	Cursor.visible = false;
}

if (Input.GetKeyDown(KeyCode.Escape))
{
	Cursor.lockState = CursorLockMode.None;
	Cursor.visible = true;
}

This allows us to lock the hide the cursor and lock it’s movement when the mouse button is pushed. As well, we add in some code to handle unlocking (and unhiding) when the Escape key is pressed.

Now add this script to an object in the scene—it doesn’t necessarily have to be added to your player object, since it doesn’t reference any scripts on variables on it. On starting the game now the mouse will be hidden and locked to the center of the screen.

Lesson 10 Complete Project


Thanks for reading! If you have any problems with the above tutorial, general comments or suggestions, please post below. It’s always appreciated!

12 thoughts on “Unity Beginner to Hero Part 10: Damaging Enemies

  1. Hi Royston Ross

    I have enjoyed this series but one thing that bugged me during testing was the fact that the mouse doesn’t lock on the screen meaning that that my mouse always went off screen.

    So can you make a future tutorial on that?

    Another thing is that maybe you should make a tutorial on basic enemy AI for this project.

    If you want to see my… creations you can see them here – http://gamejolt.com/profile/just-in/1026764

    Thanks for reading 🙂

  2. Hey I worked decently hard on my project and downloaded yours because one thing bugged out on my computer. I replaced the Assets and ProjectSettings folders and it deleted all my placed 3D Objects. Can you put a downloadable version of the finished project. So I don’t have to go through the whole thing again. Thank you.

  3. Hey, I ran into a problem, but found what was up. I got to the point where I added the

    “EnemyHealth health = col.gameObject.GetComponent();

    if (health != null)
    {
    health.TakeDamage(damageDealt);
    }”

    part, but missed that I had to change:

    ” private void OnTriggerEnter(Collider other)”

    to:

    ” private void OnTriggerEnter(Collider col)”.

    I compared scripts after a while and spotted the difference. I’m not sure if it’s mentioned anywhere to change or set it to “col” instead of “other”. Thought that was worth pointing out.

    • And as well as that, adding a value of 4 (or anything) to the “damageDealt” public variable. I guess that’s sort of self-explanatory, but I missed it anyway. Thanks again!

    • Ooops, nevermind, looks like I was the one who missed that you actually set (Collider col) when you first introduced it. My bad!

  4. Hello, I want to know why I can’t destroy these cubes if I use declare damageDealt as float, when I change it to int, it worked fine. So how make damageDealt work if I declare it as float? Thanks.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s