Search Unity

NullReferenceException when trying to drag object

Discussion in 'AR' started by Cynni, Jun 14, 2018.

  1. Cynni

    Cynni

    Joined:
    Mar 19, 2015
    Posts:
    17
    Hi,

    I'm trying to drag the spawned object only on the y-axis.
    The code works on a scene without using ARCore, but when using it in a scene with ARCore I get an NullReferenceException error. Isn't it possible to drag objects in AR?

    This is the code:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Drag : MonoBehaviour
    6. {
    7.     private Vector3 screenPoint;
    8.     private Vector3 offset;
    9.  
    10.     void OnMouseDown()
    11.     {
    12.         screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
    13.         offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    14.     }
    15.  
    16.     void OnMouseDrag()
    17.     {
    18.         Vector3 cursorPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
    19.         Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
    20.         transform.position = new Vector3(transform.position.x, cursorPosition.y, transform.position.z);
    21.     }
    22.  
    23. }
    24.  
     
  2. Cynni

    Cynni

    Joined:
    Mar 19, 2015
    Posts:
    17
    I fixed it, it didn't find the camera. So I made a camera variable and put the ar camera in it.