Search Unity

  1. Improved Prefab workflow (includes Nested Prefabs!), 2D isometric Tilemap and more! Get the 2018.3 Beta now.
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice
  4. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

NullReferenceException when trying to drag object

Discussion in 'ARCore' 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.