Search Unity

AR Foundation Tap Detection

Discussion in 'AR' started by fatihcanbekli, Aug 1, 2019.

  1. fatihcanbekli

    fatihcanbekli

    Joined:
    Aug 26, 2018
    Posts:
    1
    Hello

    I have three box on scene and I want to detect which one is selected when user tapping screen.
     
  2. ArchMageDiablo

    ArchMageDiablo

    Joined:
    Apr 4, 2012
    Posts:
    6
    Below is a script I made for simple interactions, it uses an event in the inspector to handle what to do on click. Basically it works like the default button script, except for scene objects instead of UI. I've always just used the buttons cript without issues, but suddenly that doesn't work anymore.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Events;
    5.  
    6. public class RPS_Interaction : MonoBehaviour
    7. {
    8.     public UnityEvent action;
    9.  
    10.     void Update(){
    11.         if (Input.GetMouseButtonDown(0)){
    12.             var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    13.             RaycastHit hit;
    14.             if(Physics.Raycast(ray, out hit, Mathf.Infinity)){
    15.                 GameObject obj = hit.collider.gameObject;
    16.                 obj.GetComponent<RPS_Interaction>().action.Invoke();
    17.             }
    18.         }
    19.     }
    20. }
    I had an issue with the events of any object with the script firing when any other object is clicked, so I had to add the get component there to make sure it is only affecting the clicked object, I feel like there should be a way to do this in the condition instead, but this worked for me. Also I know it's referring to mouse button, but I tested on iPad and it works with tap, haven't been able to test the script in hololens yet though.