NullReferenceException: Object reference not set to an instance of an object

Hi everybody, I’m creating a script that allows an object to “snap” to the position of another object when dropped close enough to it. I have multiple locations that the object can be snapped to, and I created a method to sort through all of the possible snap locations and find which one is closest to the current player position. However, when trying to snap to a particular location, I get an Object Reference error in line 41 of the script which reads transform.position = FindClosestPartner().transform.position;. Here is the full script.

using UnityEngine;
using System.Collections;

public class DotRearrangement : MonoBehaviour
{

    //Initializes all Snapping capabilities
    public float closeDist = 3.5f;
    public float dist = Mathf.Infinity;
    public float moveSpeed;
    public float rotationSpeed;

    public GameObject FindClosestPartner()
    {
        GameObject[] partners;
        partners = GameObject.FindGameObjectsWithTag("SnapPartner");
        GameObject closest = null;
        Vector3 myPosition = transform.position;
        foreach (GameObject partner in partners)
        {
            Vector3 diff = partner.transform.position - myPosition;
            float curDistance = diff.sqrMagnitude;
            if (curDistance < dist)
            {
                closest = partner;
                dist = curDistance;
            }
        }
        return closest;
    }

    void OnMouseDrag()
    {
        Vector3 point = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        point.z = transform.position.z;
        transform.position = point;
    }

    void OnMouseUp()
    {
        transform.position = FindClosestPartner().transform.position;
    }
}

Any help would be appreciated :slight_smile:

@Arctinium I think you can fix the problem by making your FindClosePartner method return a Vector3 not a GameObject.

public Vector3 FindClosePartner() {
    //Your code goes here and then at the end you just return the closest GameObject's position
    return closest.transform.position;
}

void OnMouseUp()
{
     transform.position = FindClosestPartner();
}

Tell me if this worked or no.

Create a new variable

public Camera myCam;

Drag the main Camera onto it and replace

Vector3 point = Camera.main.ScreenToWorldPoint(Input.mousePosition);

with

Vector3 point = myCam.ScreenToWorldPoint(Input.mousePosition);

Would have been easier if you’d posted the line number but hey you know for next time :slight_smile: