我的角色在与盒子互动时出现问题。我有一个 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();
}
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
设置为对象的实例?
这里的问题是您在错误的地方寻找 BoxManager
vì box
赋值时的组件在你的Start()
方法:
void Start () {
box = GetComponent();
}
GetComponent()
将搜索组件 BoxManager
hiện hữu当前脚本的游戏对象上(在本例中为 PlayerBox
的游戏对象)。但是,根据您的措辞,它听起来像 BoxManager
Và PlayerBox
在两个不同的游戏对象上,所以你无法通过这种方式找到组件。尝试这样做只会给出 box
vô giá trị
的值,这就是您调用 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();
box.Open();
Debug.Log("aperto " + box);
}
}
}
希望对您有所帮助!如果您有任何问题,请告诉我。
Tôi là một lập trình viên xuất sắc, rất giỏi!