Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

tap detection on a gameobject

Discussion in 'Editor & General Support' started by unity_ybf9DJzDxZsQRw, Nov 24, 2017.

  1. unity_ybf9DJzDxZsQRw

    unity_ybf9DJzDxZsQRw

    Joined:
    Nov 19, 2017
    Posts:
    2
    Hello! i'm trying to make a simple Android game in which i have to tap on an object.
    the problem is that when i attach my script to the main camera I get results no matter where i touch, but i want only if i touch on my gameobject collider.
    btw im using 2D mode. this is the script :

    void Update()
    {
    if ((Input.touchCount > 0) && (Input.GetTouch(0).phase == TouchPhase.Began))
    {
    Ray raycast = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
    RaycastHit raycastHit;
    if (Physics.Raycast(raycast, out raycastHit))
    {
    if (raycastHit.collider.CompareTag("Egg")) // (no, i didnt forget to add a tag)
    {
    //what i want to do.
    }
    }
    }
    }
    }


    after using raycast I dont get any results at all :/.
     
  2. Mazer83

    Mazer83

    Joined:
    Mar 14, 2016
    Posts:
    19
    I don't know why that's not working, but an easier option would be to just have a world-space button as a child of the GameObject.

    Edit: You'd make the button invisible of course, and you could also give the button a collider, if you want a collider that isn't a rectangle.