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 ![]()
@HaykAv Okay, I tried doing that and rewriting line 41 to look like
– david_kuehntransform.position = FindClosestPartner();but it still gives me the error when I run the game every time I release the mouse button. Any ideas? Also thanks for the quick response!