获取组件:NullReferenceException
GetComponent: NullReferenceException
我收到以下错误:
NullReferenceException: Object reference not set to an instance of an object
尝试在此行拾取对象时:
Ray ray = mainCamera.GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y));
完整代码:
using UnityEngine;
using System.Collections;
public class pickupobject :
MonoBehaviour {
GameObject mainCamera;
public float distance;
GameObject carryObject;
bool carrying;
void start() {
mainCamera = GameObject.FindWithTag("MainCamera");
}
void pickup()
{
if (Input.GetKeyDown(KeyCode.F))
{
int x = Screen.width / 2;
int y = Screen.height / 2;
Ray ray = mainCamera.GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y));
// Debug.DrawRay(ray.origin, ray.direction * 10, Color.yellow);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
pickupcube p = hit.collider.GetComponent<pickupcube>();
if (p != null)
{
carrying = true;
carryObject = p.gameObject;
}
}
}
}
void carry(GameObject o)
{
o.GetComponent<Rigidbody>().isKinematic = true;
o.transform.position = mainCamera.transform.position + mainCamera.transform.forward * distance;
}
// Update is called once per frame
void Update()
{
if (carrying)
{
carry(carryObject);
}
else
{
pickup();
}
}
}
尝试像这样写同一行:
Ray ray = Camera.main.gameObject.GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y, 0));
首先,FindWithTag 和任何 Find 都非常广泛(在你的情况下并不重要,因为你只调用它一次,但只是为了记录在案),你应该检查那里的拼写并试验 Debug.Log();打印到 mainCamera、Ray 等的控制台值...并查看何时会出现意想不到的结果。现在试试我的代码,它几乎是一样的,只是使用不同的相机引用
我收到以下错误:
NullReferenceException: Object reference not set to an instance of an object
尝试在此行拾取对象时:
Ray ray = mainCamera.GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y));
完整代码:
using UnityEngine;
using System.Collections;
public class pickupobject :
MonoBehaviour {
GameObject mainCamera;
public float distance;
GameObject carryObject;
bool carrying;
void start() {
mainCamera = GameObject.FindWithTag("MainCamera");
}
void pickup()
{
if (Input.GetKeyDown(KeyCode.F))
{
int x = Screen.width / 2;
int y = Screen.height / 2;
Ray ray = mainCamera.GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y));
// Debug.DrawRay(ray.origin, ray.direction * 10, Color.yellow);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
pickupcube p = hit.collider.GetComponent<pickupcube>();
if (p != null)
{
carrying = true;
carryObject = p.gameObject;
}
}
}
}
void carry(GameObject o)
{
o.GetComponent<Rigidbody>().isKinematic = true;
o.transform.position = mainCamera.transform.position + mainCamera.transform.forward * distance;
}
// Update is called once per frame
void Update()
{
if (carrying)
{
carry(carryObject);
}
else
{
pickup();
}
}
}
尝试像这样写同一行:
Ray ray = Camera.main.gameObject.GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y, 0));
首先,FindWithTag 和任何 Find 都非常广泛(在你的情况下并不重要,因为你只调用它一次,但只是为了记录在案),你应该检查那里的拼写并试验 Debug.Log();打印到 mainCamera、Ray 等的控制台值...并查看何时会出现意想不到的结果。现在试试我的代码,它几乎是一样的,只是使用不同的相机引用