Menu
CoddyTech

敌人数据

Coddy Unity 塔防游戏 课程的第 2 课,共 25 课。

一个 Runner 加入了 Grunt。它速度更快,生命值更低,而且所有 Runner 的这两个数值都相同,所以这些数值属于这种敌人,而不是某一个敌人。它们存储在指定的 EnemyData(一种 ScriptableObject 资源)中:项目中有 GruntData(速度 2,生命值 9)和 RunnerData(速度 3.5,生命值 5),Inspector 会在 data 字段中为每个敌人指定对应的数据。

每个敌人每次需要数值时,都会通过这个字段读取所属类型的数值:

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

生命值则不同:受到攻击的 Grunt,生命值会比它后面的 Grunt 少。因此,资源中保存的是 maxHealth,每个敌人都会在 Awake 中将它复制到自己的字段里。对象一创建,Awake 就会运行。不要修改资源本身,否则这种类型的所有敌人都会受到影响。

challenge icon

挑战

简单

让每个敌人从自己的资源中获取对应类型的属性。

  1. 在 Enemy 中,用 public EnemyData data; 替换 speed,并以 data.speed 的速度移动。
  2. 添加 private int health;,并在 Awake 中将它设为 data.maxHealth。

按“开始”:Runner 会超过 Grunt。然后按“检查”。

亲手试试

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++;
        }
    }
}

Unity 塔防游戏中的所有课

自己练习: Unity 在线编辑器