Search Unity

OnMouseDown with Collider2D

Discussion in 'Scripting' started by ykosyakov, Nov 15, 2013.

Thread Status:
Not open for further replies.
  1. ykosyakov

    ykosyakov

    Joined:
    Nov 10, 2012
    Posts:
    6
    Hello!

    OnMouseDown function work with 2D Colliders? I add collider to object, and script with OnMouseDown, but it doesn't work :(

    Thanks for help!
     
  2. unitylover

    unitylover

    Joined:
    Jul 6, 2013
    Posts:
    346
    OnMouseDown does in fact work with Collider2D, not sure why you are having problems. Paste your code if you don't want to you my method below.

    Code (csharp):
    1.  
    2. void Update() {
    3.     if (Input.GetMouseButton(0))
    4.         Debug.Log("Mouse down");
    5. }
     
    Last edited: Nov 15, 2013
    sxz7 and r10101 like this.
  3. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    ykosyakov is referring to MonoBehaviour.OnMouseDown.
     
  4. ykosyakov

    ykosyakov

    Joined:
    Nov 10, 2012
    Posts:
    6
    I mean:
    void OnMouseDown ()
    {
    //something
    }
     
  5. Storyteller

    Storyteller

    Joined:
    May 15, 2012
    Posts:
    23
    I had trouble getting it to work at first, but it does work.
     
  6. Martin12

    Martin12

    Joined:
    Nov 13, 2013
    Posts:
    6
    Would you mind sharing what your problem was, and how you resolved it? It doesn't work for me, either, and I don't know what to change.
     
    Alex_May likes this.
  7. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    Works fine for me, I didn't have to do anything special. I'm using a Box Collider 2D.
     
  8. AlanOToole

    AlanOToole

    Joined:
    Sep 7, 2013
    Posts:
    132
    I just took a fresh copy of the 2D platformer and added this script to the Hero (C#):

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class TickleWithMouse : MonoBehaviour {
    5.  
    6.     // Use this for initialization
    7.     void Start () {
    8.    
    9.     }
    10.    
    11.     // Update is called once per frame
    12.     void Update () {
    13.  
    14.     }
    15.  
    16.     void OnMouseDown()
    17.     {
    18.         Debug.Log ("Stop that, it tickles!");
    19.     }
    20. }
    And it works out of the box as long as the object you are using has a 2D Collider of some sort. Hopefully this helps a bit.
     
    unity_rwmmTlXSuVlWVA likes this.
  9. Martin12

    Martin12

    Joined:
    Nov 13, 2013
    Posts:
    6
    My issue turned out to be that another object in the background was somehow blocking the mouse detection. Moving it to another camera culling mask fixed it.
     
    alexjhones286 likes this.
  10. AlanOToole

    AlanOToole

    Joined:
    Sep 7, 2013
    Posts:
    132
    Very good to know! Thanks for sharing.
     
  11. fc

    fc

    Joined:
    Jun 21, 2013
    Posts:
    1
    I've had a similar problem using unity 4.3.1. Tried removing all game objects except the one with OnMouseDown. Created a new object with the OnMouseDown script. Nothing helped.

    I then created a new project, pasted over the same code and everything worked. Weird.
     
    Last edited: Nov 30, 2013
  12. vinfang

    vinfang

    Joined:
    Jul 13, 2013
    Posts:
    14
    Just wanted to add some more info on this. I created 2D game with everything on the XY plane and using the left hand rule, the camera is facing down the positive Z axis. Have a 3D object and a 2D object in the same X, Y, but different Z location, some reason the 3D object always receives all the mouse clicks, even if the 2D object is in front of the 3D object on the Z axis.

    I tried putting the 2D object behind the 3D object and the result is still the same, the 3D object receives the mouse click instead of the 2D object.

    I disabled my 3D background plane and ran the game again, and now my 2D object was receiving the mouse clicks.
     
    XelX0r likes this.
  13. TetraDB

    TetraDB

    Joined:
    Jun 7, 2014
    Posts:
    1
    I had a similar issue, but im my case I had overlapping collision boxes. So I had to manage the layer of the gameobject that had those colliders, because one collider was taking the mousedown event before the other, and I think its was simply down the the order I created stuff.
     
  14. tronglv

    tronglv

    Joined:
    Dec 7, 2013
    Posts:
    21
    using Box Collider
     
  15. mattjcody

    mattjcody

    Joined:
    Jul 10, 2013
    Posts:
    2
    This is an old thread but I'm going to post anyway in hope that someone has some new info.

    I'm experiencing this problem right now. I quick run down is that I've got two types of game objects. Tiles and Slots. Tiles can be moved around on the screen and placed into slots. Everything seems to be working except occasionally, I couldn't get the dragging script to work on my tiles.

    I eventually worked out its because the OnMouseDown on the slot was firing instead of the tile. Even though the tile collider completely covers the slot collider and the graphics for the tile was definitely on top of the slot, it was still blocking it.

    This behaviour is very consistent. A couple of minutes ago I put down about 5 tiles and 10 slots. I started randomly dragging around until on of the tiles got stuck. I compared the properties of a stuck tile and slot to one that was working properly and they were pretty much identical.

    Has anyone experienced this or worked out a way around it. I've tried setting up new layers, I've tried recreating all the objects in the scene in a different order. I've tried lots of things but at this point, its completely ruined the progress of my game.

    Any help would be greatly appreciated!
     
    pigaroos likes this.
  16. Pyrian

    Pyrian

    Joined:
    Mar 27, 2014
    Posts:
    301
    I can see how that would be annoying, but isn't it pretty easy to work around using Input? Shouldn't be a show-stopper.
     
  17. Xand3r

    Xand3r

    Joined:
    Mar 28, 2013
    Posts:
    5
    Hi there!

    I had kind of the same problem with the 2D environment of Unity.

    In my case, my problem was that I had a GameObject with a big Polygon Collider2D, in this I had placed a smaller Box Collider2D. The mouse events wouldn't recognize the smaller, as (I think) it was merged to the parent's bigger collider or something.

    I searched the internet, but couldn't find anyone with the same problem.
    I did solve it, and with thanks to this forum post I came up with a solution to this problem.

    Code (CSharp):
    1.  
    2.         public GameObject hoveredGO,lastHoveredGO;
    3.         public enum HoverState { HOVER, NONE };
    4.         public HoverState hover_state = HoverState.NONE;
    5.         [HideInInspector]public Collider2D currentButton = null;
    6.  
    7.         void Update()
    8.         {
    9.             Vector3 wp = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    10.             Vector2 touchPos = new Vector2(wp.x, wp.y);
    11.             Collider2D[] currentButtons = Physics2D.OverlapPointAll(touchPos);
    12.             if (currentButtons.Length > 0)
    13.             {
    14.              
    15.                 float closestPosition = Mathf.Infinity;
    16.                 foreach(Collider2D col in currentButtons)
    17.                 {
    18.                     if (col.transform.position.z < closestPosition)
    19.                     {
    20.                         closestPosition = col.transform.position.z;
    21.                         currentButton = col;
    22.                     }
    23.                 }
    24.                 if (hover_state == HoverState.NONE)
    25.                 {
    26.                     currentButton.SendMessage("OnMouseButtonEnter", SendMessageOptions.DontRequireReceiver);
    27.                     hoveredGO = currentButton.gameObject;
    28.                 }
    29.                 else if (currentButton != lastHoveredGO)
    30.                 {
    31.                     lastHoveredGO.SendMessage("OnMouseButtonExit", SendMessageOptions.DontRequireReceiver);
    32.                     hoveredGO = currentButton.gameObject;
    33.                 }
    34.                 hover_state = HoverState.HOVER;
    35.             }
    36.             else
    37.             {
    38.                 if (hover_state == HoverState.HOVER)
    39.                 {
    40.                     hoveredGO.SendMessage("OnMouseButtonExit", SendMessageOptions.DontRequireReceiver);
    41.                 }
    42.                 hoveredGO = null;
    43.                 hover_state = HoverState.NONE;
    44.             }
    45.  
    46.             if (hover_state == HoverState.HOVER)
    47.             {
    48.                 currentButton.SendMessage("OnMouseButtonOver", SendMessageOptions.DontRequireReceiver); //Mouse is hovering
    49.                 if (Input.GetMouseButtonDown(0))
    50.                 {
    51.                     currentButton.SendMessage("OnMouseButtonDown", SendMessageOptions.DontRequireReceiver); //Mouse down
    52.                 }
    53.                 if (Input.GetMouseButtonUp(0))
    54.                 {
    55.                     currentButton.SendMessage("OnMouseButtonUpAsButton", SendMessageOptions.DontRequireReceiver); //Mouse up as button
    56.                 }
    57.  
    58.             }
    59.             lastHoveredGO = hoveredGO;
    60.         }
    Make a script of this, and place it on a "InputHandler" object or something. It only needs to be in the scene once.
    Instead of the standard OnMouseEnter event, use the new OnMouseButtonEnter (or rename it to something custom) to be sure you don't get double events triggered!
    Also, as seen in the script, this arranges the prefered collider with the Z-axis of it's GameObject.

    I hope I can help someone with this result, as it took me some time to figure it out myself.

    And my question to the masters: is this a known bug or is there a button I didn't press somewhere?
     
    DimBimbleby likes this.
  18. FranciscoFontes

    FranciscoFontes

    Joined:
    Jul 12, 2014
    Posts:
    3
    Hello, my solution is to create the observer pattern.

    MouseManager will check the objects you want to know about mouse events or states of the mouse.

    IMouseObserver is implemented to perform the specific behavior of each mouse event

    http://www.orunz.com/tuto/mouse_manager.unitypackage
     
  19. gudus

    gudus

    Joined:
    Sep 18, 2014
    Posts:
    1
    Try add Rigidbody2D to object, it's works for me...
     
    marshallas and fkgfw like this.
  20. agora

    agora

    Joined:
    Apr 12, 2014
    Posts:
    23
    I had the same problem,
    And found quite a number of posts regarding this issue,
    Unity2d apparently has no definite order which collider2d is recognized using onmouseclick and will just choose a random one if colliders are overlapping.

    The best solution is to detect where the mouse is clicked using raycast, and then detect if the object you need is in this position.

    This is one of the many posts about this:
    http://answers.unity3d.com/questions/598492/how-do-you-set-an-order-for-2d-colliders-that-over.html

    good luck
     
  21. fkgfw

    fkgfw

    Joined:
    Sep 1, 2015
    Posts:
    1
    thx,i fixed this problem by add a rigidbody 2d
     
  22. Halmato

    Halmato

    Joined:
    Jan 14, 2016
    Posts:
    1
    Try setting the Render Mode of the Canvas that your object is on, to "Screen Space - Camera", and select your Main Camera as the Render Camera.
     
    antonio_iliev likes this.
  23. Canhuo233

    Canhuo233

    Joined:
    Oct 7, 2016
    Posts:
    1
    I think there's a method better than OnMouse.
    You can add Component "EventTrigger"to GO,write method in scripts,then click the Add New Event Type button of the EventTrigger to add what you want
     
    CzlLebleu, thanhtam2a and jERRYN35 like this.
  24. jERRYN35

    jERRYN35

    Joined:
    Oct 30, 2016
    Posts:
    2
    You were right thanks. I added event OnPointerClickand everything is ok. Thx again.
     
  25. alexjhones286

    alexjhones286

    Joined:
    Mar 28, 2016
    Posts:
    5
    Obrigado'. Brasil aqui'.
     
  26. antonio_iliev

    antonio_iliev

    Joined:
    Feb 28, 2019
    Posts:
    1
    It works for me.
     
  27. Maels_Mo

    Maels_Mo

    Joined:
    Aug 15, 2019
    Posts:
    5
    Check your input system, onMouse... events works only with old input system.
     
    madbuggerswall and Viole like this.
Thread Status:
Not open for further replies.