Search Unity

detect a touch on a GameObject

Discussion in '2D' started by immeasur, Nov 21, 2013.

  1. immeasur

    immeasur

    Joined:
    Dec 12, 2010
    Posts:
    3
    I'm developing a 2D game on Unity 4.3, using 2D features.

    I'm trying to write a script to check multiple touches and detect which sprite/gameobject the player has tapped.

    I could detect a touch but I'm not able to find the solution to access the object if it's tapped.

    The only solution I found closely related to the issue I'm having is here:

    but it's not the one I'm looking for, I need to access the gameobject that the player tapped so that I can change it's color and scale value.

    Can anyone suggest a better way to do it?
     
  2. Mogitu

    Mogitu

    Joined:
    Nov 13, 2013
    Posts:
    40
    i used the bounds of the object to detect if the current touch/click position is inside.

    if(renderer.bounds.contains(somePosition))
    {
    //do cool stuff
    }
     
  3. Elejdor

    Elejdor

    Joined:
    Nov 21, 2013
    Posts:
    1
    There is also a generic Unity event OnMouseEnter/Down/Over. To use that you need a collider on your object and then you have to define a function inside a script assigned to the object.

    Code (csharp):
    1.  
    2. //This function is called when mouse is directly over a collider
    3. void OnMouseOver()
    4. {
    5.        DoSomething();
    6. }
    7.  
    Edit: I noticed an issue. When you have a 3d collider and 2d collider the function is called by 3d collider even if it's behind the 2d one.