Menu
CoddyTech

Enemy Data

Lesson 2 of 25 in Coddy's Unity Game: Tower Defense course.

A Runner joins the Grunt. It is faster and has less health, and every Runner shares those numbers, so they belong to the kind, not to one enemy. They live in the given EnemyData, a ScriptableObject asset: the project has GruntData (speed 2, health 9) and RunnerData (speed 3.5, health 5), and the Inspector gives each enemy its own in a data field.

Each enemy reads its kind's numbers through that field, every time it needs them:

void Start()
{
    Debug.Log(name + " pays " + data.reward);
}

Health is different: a Grunt that took a hit has less than the Grunt behind it. So the asset holds maxHealth, and each enemy copies it into a field of its own in Awake, which runs as soon as the object is made. Never change the asset itself: every enemy of the kind would change.

challenge icon

Challenge

Easy

Give each enemy its kind's stats from its asset.

  1. In Enemy, replace speed with public EnemyData data; and walk at data.speed.
  2. Add private int health; and set it to data.maxHealth in Awake.

Press Play: the Runner overtakes the Grunt. Then Check.

Try it yourself

using UnityEngine;

public class Enemy : MonoBehaviour
{
    public float speed = 2f;
    public Transform[] waypoints;

    private int next = 1;

    void Update()
    {
        if (next >= waypoints.Length)
        {
            return;
        }

        Vector3 target = waypoints[next].position;
        transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
        if (transform.position == target)
        {
            next++;
        }
    }
}

All lessons in Unity Game: Tower Defense

Practice on your own: Unity playground