Menu
CoddyTech

拾取物

本课属于 Coddy Unity 学习旅程的“物理与游戏玩法”单元。第 17 课,共 71 课。

拾取物是一个自带脚本的触发器。有物体进入时,拾取物会检查它是否是玩家,然后将效果交给它,并销毁自身。玩家的脚本会保存结果,并为此提供一个公共方法。这个生命值补给包会治疗任何带有 Health 脚本的对象:

// HealthPack.cs
public int amount = 25;

void OnTriggerEnter(Collider other)
{
    if (other.TryGetComponent(out Health health) && health.hp < 100)
    {
        health.Heal(amount);
        Destroy(gameObject);
    }
}
// Health.cs,挂在玩家对象上
public int hp = 50;

public void Heal(int amount)
{
    hp = Mathf.Min(hp + amount, 100);
    Debug.Log("HP: " + hp);
}

对于滑进补给包的箱子,other.TryGetComponent(out Health health) 的结果是 false,所以只有带有 Health 脚本的对象才能拾取它;生命值已满的玩家则会把补给包留到之后再用。补给包通过 other 找到玩家,因此不需要在 Inspector 中设置引用,一个关卡里可以放 50 个补给包。Heal 是 public,因为另一个脚本会调用它;生命值上限 100 则由 Health 管理,因为它是唯一负责 hp 的地方。Destroy(gameObject) 会移除补给包;Destroy(other.gameObject) 则会移除玩家。

challenge icon

挑战

简单

让弹药箱为 Blaster 补充弹药(ammo 为 4,maxAmmo 为 10)。

  1. 在 Blaster.cs 中,添加 public int AddAmmo(int amount):int taken = Mathf.Min(amount, maxAmmo - ammo);,将其加到 ammo 中,记录 "Ammo: " + ammo,并返回 taken。
  2. 在 AmmoCrate.cs 中,当满足 other.TryGetComponent(out Blaster blaster) 时,调用 blaster.AddAmmo(amount); 和 Destroy(gameObject);。

按下“开始”并向右走:控制台会显示 Ammo: 7,然后显示 Ammo: 10。接着点击“检查”。

亲手试试

using UnityEngine;

public class AmmoCrate : MonoBehaviour
{
    public int amount = 3;

    void OnTriggerEnter(Collider other)
    {
        // 玩家的 Blaster 拿走弹药后,弹药箱就会消失
    }
}

物理与游戏玩法中的所有课

自己练习: Unity 在线编辑器