Search Unity

  1. Get all the Unite Berlin 2018 news on the blog.
    Dismiss Notice
  2. Unity 2018.2 has arrived! Read about it here.
    Dismiss Notice
  3. Improve your Unity skills with a certified instructor in a private, interactive classroom. Learn more.
    Dismiss Notice
  4. ARCore is out of developer preview! Read about it here.
    Dismiss Notice
  5. Magic Leap’s Lumin SDK Technical Preview for Unity lets you get started creating content for Magic Leap One™. Find more information on our blog!
    Dismiss Notice
  6. 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.