我是新手Unity开发者,试图在游戏中实现拖放系统,遵循了YouTube上的这个指南,但是按照指南后,返回了这个错误信息:
NullReferenceException: 对象引用不为 null。
Drag.OnDrag (UnityEngine.EventSystems.PointerEventData eventData) (at Assets/drag.cs:10)
UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IDragHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at ./Library/PackageCache/com.unity.ugui@67707a67a4ab/Runtime/UGUI/EventSystem/ExecuteEvents.cs:78)
UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) (at ./Library/PackageCache/com.unity.ugui@67707a67a4ab/Runtime/UGUI/EventSystem/ExecuteEvents.cs:272)
UnityEngine.EventSystems.EventSystem:Update() (at ./Library/PackageCache/com.unity.ugui@67707a67a4ab/Runtime/UGUI/EventSystem/EventSystem.cs:516)
我的代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Drag : MonoBehaviour, IPointerDownHandler, IDragHandler
{
private Vector2 _distance;
public void OnDrag(PointerEventData eventData)
{
_distance = Camera.main.ScreenToWorldPoint(eventData.position) - transform.position;
}
public void OnPointerDown(PointerEventData eventData)
{
Vector2 pointerPosition = Camera.main.ScreenToWorldPoint(eventData.position);
Vector2 newObjectPosition = pointerPosition - _distance;
transform.position = newObjectPosition;
}
}
我已经添加了事件系统和射线2D,按照视频指示,但错误仍然显示。希望得到帮助,感谢。
评论 (0)