缺少组件
本课属于 Coddy Unity 学习旅程的“Unity 脚本基础”单元。第 45 课,共 85 课。
如果你要查找的组件不在对象上,GetComponent 不会阻止你。在 Editor 中,它会返回一个与 null 相等的替代对象,而你的代码第一次使用它时,Unity 就会抛出异常。按下 Space 时,这个球应该跳起来,但它没有添加 Rigidbody:
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector3.up * 300f);
}
}按下 Space 会显示 MissingComponentException: There is no 'Rigidbody' attached to the "Ball" game object, but a script is trying to access it.。这条消息指出了缺失的类型和对象。你可以在 Inspector 中添加该组件;如果对象可能是有意不添加该组件,则应先进行检查。组件存在时,TryGetComponent(out rb) 会返回 true 并将组件赋给 rb;组件不存在时,它会返回 false,且不会报错(out 允许方法通过变量返回一个值):
bool canHop;
void Start()
{
canHop = TryGetComponent(out rb);
}接下来,Update() 只会在 if (canHop) 条件成立时推动球。在 Editor 之外的已构建游戏中,GetComponent 会返回普通的 null,因此同样的错误会以 NullReferenceException 的形式出现。
挑战
中等Lamp2 没有 Light:让 Space 键跳过它,并显示它已损坏。
- 在
Start()中,将GetComponent这一行替换为hasBulb = TryGetComponent(out bulb);,并添加一个bool hasBulb;字段。 - 当
hasBulb为 false 时,将灯的颜色设为灰色:GetComponent<Renderer>().material.color = Color.gray;。 - 在
Update()中,仅当hasBulb为 true 时切换灯光。
按下“开始”并按 Space 键:正常的灯会切换,且不会出现错误。然后按“检查”。
亲手试试
using UnityEngine;
public class LampSwitch : MonoBehaviour
{
Light bulb;
void Start()
{
bulb = GetComponent<Light>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
bulb.enabled = !bulb.enabled;
}
}
}
Unity 脚本基础中的所有课
自己练习: Unity 在线编辑器