试图用鼠标统一拖动一个对象,我不断收到同样的错误
Trying to drag an object with mouse in unity, I keep getting the same error
脚本已附加到我尝试拖动的游戏对象,错误状态为:
NullReferenceException,对象引用未设置到对象的实例
它指向我脚本的第 25 行:
distance = Vector3.Distance(transform.position, Camera.main.transform.position);
这是完整的脚本:
using System.Collections;
using UnityEngine;
class DragTransform : MonoBehaviour
{
private Color mouseOverColor = Color.blue;
private Color originalColor = Color.yellow;
private bool dragging = false;
private float distance;
void OnMouseEnter()
{
GetComponent<Renderer>().material.color = mouseOverColor;
}
void OnMouseExit()
{
GetComponent<Renderer>().material.color = originalColor;
}
void OnMouseDown()
{
distance = Vector3.Distance(transform.position, Camera.main.transform.position);
dragging = true;
}
void OnMouseUp()
{
dragging = false;
}
void Update()
{
if (dragging)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 rayPoint = ray.GetPoint(distance);
transform.position = rayPoint;
}
}
}
非常感谢大家的帮助!谢谢!
如果没有相机标记为 MainCamera
,Camera.main
将 return 为空。
https://docs.unity3d.com/ScriptReference/Camera-main.html
您需要将主摄像头标记为MainCamera
。
脚本已附加到我尝试拖动的游戏对象,错误状态为:
NullReferenceException,对象引用未设置到对象的实例
它指向我脚本的第 25 行:
distance = Vector3.Distance(transform.position, Camera.main.transform.position);
这是完整的脚本:
using System.Collections;
using UnityEngine;
class DragTransform : MonoBehaviour
{
private Color mouseOverColor = Color.blue;
private Color originalColor = Color.yellow;
private bool dragging = false;
private float distance;
void OnMouseEnter()
{
GetComponent<Renderer>().material.color = mouseOverColor;
}
void OnMouseExit()
{
GetComponent<Renderer>().material.color = originalColor;
}
void OnMouseDown()
{
distance = Vector3.Distance(transform.position, Camera.main.transform.position);
dragging = true;
}
void OnMouseUp()
{
dragging = false;
}
void Update()
{
if (dragging)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 rayPoint = ray.GetPoint(distance);
transform.position = rayPoint;
}
}
}
非常感谢大家的帮助!谢谢!
MainCamera
,Camera.main
将 return 为空。
https://docs.unity3d.com/ScriptReference/Camera-main.html
您需要将主摄像头标记为MainCamera
。