Search Unity

  1. Unity 2019.1 beta is now available.
    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. We're looking for insight from anyone who has experience with game testing to help us better Unity. Take our survey here. If chosen to participate you'll be entered into a sweepstake to win an Amazon gift card.
    Dismiss Notice
  4. Want to provide direct feedback to the Unity team? Join the Unity Advisory Panel.
    Dismiss Notice
  5. Unity 2018.3 is now released.
    Dismiss Notice
  6. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    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.