gpt4 book ai didi

c# - 尝试与光线转换命中的对象上的组件进行交互,得到 NullReferenceException

转载 作者:行者123 更新时间:2023-11-30 23:17:22 25 4
gpt4 key购买 nike

我的角色在与盒子互动时出现问题。我有一个 GameObject Player 附加了一个脚本来与游戏中的盒子交互,脚本是:

using UnityEngine;
using System.Collections;

public class PlayerBox : MonoBehaviour {

public bool active = true;
public KeyCode key = KeyCode.E;

float distance = 2F;
RaycastHit obj;
BoxManager box;

void Start () {
box = GetComponent<BoxManager>();
}

void Update () {
if (active && Input.GetKeyDown (key) && Physics.Raycast (this.transform.position, this.transform.forward, out obj, distance)) {
if (obj.collider.gameObject.tag == "Box") {
box.Open();
Debug.Log("aperto " + box);
}
}

}
}

场景中有一个 GameObject Box,其中包含用于管理行为的脚本:

using UnityEngine;
using System.Collections;

public class BoxManager : MonoBehaviour {

public void Open() {
Debug.Log ("Dentro");
}
}

最后一个脚本应该打印日志,但是当我与它交互时,我得到了

NullReferenceException: Object reference not set to an instance of an object PlayerBox.Update () (at Assets/ETSMB/Script/Use/PlayerBox.cs:23)

如何正确地将 box 设置为对象的实例?

最佳答案

这里的问题是您在错误的地方寻找 BoxManagerbox 赋值时的组件在你的Start()方法:

void Start () {
box = GetComponent<BoxManager>();
}

GetComponent<BoxManager>()将搜索组件 BoxManager当前脚本的游戏对象上(在本例中为 PlayerBox 的游戏对象)。但是,根据您的措辞,它听起来像 BoxManagerPlayerBox在两个不同的游戏对象上,所以你无法通过这种方式找到组件。尝试这样做只会给出 box null 的值,这就是您调用 box.Open() 时出现 NullReferenceException 的原因.

您需要做的是检索 BoxManager从你从 Physics.Raycast() 得到的对象- 所以删除你的 Start() 里的东西方法,并重写你的 Update() 的内容方法:

void Update () {
if (active && Input.GetKeyDown (key) && Physics.Raycast (this.transform.position, this.transform.forward, out obj, distance)) {
if (obj.collider.gameObject.tag == "Box") {
// Get the BoxManager from the object that has been hit
box = obj.collider.gameObject.GetComponent<BoxManager>();
box.Open();
Debug.Log("aperto " + box);
}
}
}

希望对您有所帮助!如果您有任何问题,请告诉我。

关于c# - 尝试与光线转换命中的对象上的组件进行交互,得到 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41468940/

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