Menu
CoddyTech

按名称查找

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

GameObject.Find("Player")会在场景中搜索名称完全匹配的活动对象,并返回该对象;如果没有匹配项,则返回 null。这样就不必在 Inspector 中设置字段,但代价是要遍历场景中的每个对象。因此,只在 Start() 中调用一次,并将结果保存在字段中。这台监控摄像机会在游戏开始时找到 Player,并在每一帧监视它:

private Transform player;

void Start()
{
    player = GameObject.Find("Player").transform;
}

void Update()
{
    transform.LookAt(player);
}

名称必须完全匹配,包括大小写和空格:"player" 或 "Player " 都找不到对象。Find 也会跳过未激活(隐藏)的对象。搜索失败时会静默返回 null,错误会在下一行使用搜索结果的代码中出现:在这里,.transform 会引发 NullReferenceException。像 "Car/Wheel" 这样的路径会找到 Car 的子对象 Wheel。

challenge icon

挑战

中等

探测车会报告它距离目标有多远。

  1. 在 Start() 中,设置 goal = GameObject.Find("Goal").transform;。
  2. 在 Update() 中,当按下 Input.GetKeyDown(KeyCode.Space) 时,记录 "Distance to goal: " + Vector3.Distance(transform.position, goal.position)。

按“开始”,然后按 Space:控制台会显示 Distance to goal: 5。然后点击“检查”。

亲手试试

using UnityEngine;

public class Beacon : MonoBehaviour
{
    private Transform goal;

    void Start()
    {
        // 找到名为 Goal 的对象,并将其 Transform 保存在 goal 中。
    }

    void Update()
    {
        // Space:记录到目标的距离。
    }
}

Unity 脚本基础中的所有课

自己练习: Unity 在线编辑器