Menu
CoddyTech

回顾:最近的金币

本课属于 Coddy Unity 学习旅程的“Unity 脚本基础”单元。第 61 课,共 85 课。

本次回顾将本章内容串联起来:在需要时按标签搜索,遍历搜索结果,并计算到每个对象的距离。

challenge icon

挑战

中等

给玩家添加一个硬币雷达:按下空格键即可显示最近的硬币。

  1. 按下空格键时,先使用 GameObject nearest = null; 和 float best = Mathf.Infinity;。
  2. 遍历 GameObject.FindGameObjectsWithTag("Coin") 中的每枚硬币,如果它到玩家的距离小于 best,就保留它。
  3. 记录 "Nearest coin: " + nearest.name。

按下“开始”,移动玩家并按下空格键:控制台会显示 Nearest coin: Silver。然后点击“检查”。

亲手试试

using UnityEngine;

public class CoinRadar : MonoBehaviour
{
    [SerializeField] private float speed = 4f;

    void Update()
    {
        if (Input.GetKey(KeyCode.RightArrow))
        {
            transform.position += new Vector3(speed * Time.deltaTime, 0, 0);
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            transform.position -= new Vector3(speed * Time.deltaTime, 0, 0);
        }
        if (Input.GetKey(KeyCode.UpArrow))
        {
            transform.position += new Vector3(0, 0, speed * Time.deltaTime);
        }
        if (Input.GetKey(KeyCode.DownArrow))
        {
            transform.position -= new Vector3(0, 0, speed * Time.deltaTime);
        }

        // 空格键:记录最近一枚金币的名称。
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

Unity 脚本基础中的所有课

自己练习: Unity 在线编辑器