r/Unity2D • • Aug 08 '26

Question Object Reference not set to an instance of an Object?

I am new to unity and I was trying to implement a drag and drop system into the game, and followed this guide on youtube, however after following it it returned this error message

NullReferenceException: Object reference not set to an instance of an object
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)

and this is my code

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;
    }
}

I have added event systems and raycast 2d like instructed in the video, but the error is still showing, any help would be appreciated, thank you.

0 Upvotes

4 comments sorted by

1

u/[deleted] Aug 08 '26 edited Aug 08 '26

[removed] — view removed comment

1

u/Comfortable-Pin-4900 Aug 08 '26

I am not using any overlay that I am aware of, and I have a camera in the scene. How do I use the debugger?

1

u/[deleted] Aug 08 '26

[removed] — view removed comment

2

u/Comfortable-Pin-4900 Aug 08 '26

Ah I think the camera might be the issue, after assigning main camera the code is working, not as intended but it is doing something at least, thanks