gpt4 book ai didi

c# - GetComponent 返回 null

转载 作者:行者123 更新时间:2023-11-30 20:32:48 26 4
gpt4 key购买 nike

在 Unity 5.4/5.5 中,我遇到了一个问题,GetComponent 由于某种原因没有返回我的游戏对象的 CharacterController。在我重新启动 Unity 后,它再次工作。

enter image description here

_MAIN 运行这个脚本:

private GameObject frog;
private CharacterController controller;

void Start () {
frog = GameObject.Find ("Frog");
controller = frog.GetComponent<CharacterController> ();

Debug.Log(controller); // returns null
}

void Update () {
if (controller.isGrounded) {
// error is thrown
}
}

在Update中引用了controller之后,报错:

MissingComponentException: There is no 'CharacterController' attached to the "Frog" game object,

仅供引用,frog 返回 GameObject 就好了。

最佳答案

尝试使用 GameObject.FindWithTag("Frog") 并将标签“Frog”添加到 Frog 对象,而不是使用 GameObject.Find("Frog")

发生这种情况的原因是不知何故,在某个地方,第二个名为“ Frog ”的对象被添加到场景中。发生这种情况时,Unity 会随机选择它找到的两个对象之一,这会导致它有时工作但有时不工作。

通过切换到标签,您更有可能对对象进行唯一标识。

关于c# - GetComponent 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40898436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com