Search code examples
c#nullreferenceexceptionunity-game-engine

Trying to drag an object with mouse in unity, I keep getting the same error


The script is attached to the gameObject I am trying to drag, the error states:

NullReferenceException, object reference not set to an instance of an object

It points to line 25 of my script which is:

distance = Vector3.Distance(transform.position, Camera.main.transform.position);

Here is the full script:

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

Any and all help greatly appreciated guys! Thanks!


Solution

  • Camera.main will return null if there is no camera tagged as MainCamera. https://docs.unity3d.com/ScriptReference/Camera-main.html

    You need to tag your main camera as MainCamera.

    enter image description here