Enemy Data
Lesson 2 of 18 in Coddy's Unity Game: Tower Defense course.
A tower defense game has kinds of enemies: grunts, fast runners, slow tanks. Every grunt walks at the same speed and starts with the same health, so those numbers belong to the kind, not to one enemy. They go in a ScriptableObject asset, one per kind, and every enemy of the kind points at it. Change the asset, and every enemy of that kind changes with it.
An asset must not hold the state of one enemy. A grunt that took a hit has less health than the grunt behind it, so the asset holds maxHealth, the health a grunt starts with, and each enemy copies it into a field of its own. A racing game splits a car the same way:
[CreateAssetMenu(fileName = "NewCar", menuName = "Racing/Car Data")]
public class CarData : ScriptableObject
{
public float topSpeed = 30f;
public float tankSize = 50f;
}
public class Car : MonoBehaviour
{
public CarData data;
private float fuel;
void Awake()
{
fuel = data.tankSize;
}
}Every car of a model shares one CarData, and each burns its own fuel. Writing data.tankSize -= used instead would drain the tank of every car of that model at once, and in the Editor the change would stay in the asset after Play. Awake runs as soon as the object is created, so the copy is ready before anything can use it.
Challenge
EasyA Runner joins the Grunt: faster, with less health. Give each kind its own asset.
- In
EnemyData.cs, make EnemyData creatable from the Create menu with the menu nameTower Defense/Enemy Data, and give it the public fieldsspeed(a float),maxHealthandreward(ints). - In
Enemy.cs, replace thespeedfield with a public fielddataof type EnemyData, and walk atdata.speed. - Add a private int
health, set to the asset'smaxHealthinAwake.
The project has a GruntData asset (speed 2, health 9, reward 5) and a RunnerData asset (speed 3.5, health 5, reward 3), and the Inspector gives each enemy its own. Press Play and watch the Runner overtake the Grunt, then Check.
Try it yourself
using UnityEngine;
// Comes later: the stats of one kind of enemy, as an asset.
public class EnemyData : ScriptableObject
{
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.