OnMouseDown and mobile?

Everything that I have looked up on subject of using OnMouseDown to trigger touch events on mobile says you should be using the touch input class and raycasting instead of OnMouseDown to detect touches, even unity says there could be performance issues in the console using OnMouseDown on mobile. I tried testing a game out using both methods, OnMouseDown and the touch input class with raycasting and saw zero change in performance at all on a bottom of the line dual core 512mb Android phone. If I am seeing no performance change are there any disadvantages to using OnMouseDown for mobile?

When building a game for a mobile device Unity examines all scripts and DLLs in the project for ANY mouse events and sets usesOnMouseEvents variable to true if it finds at least one. This variable is then used in player loop on device to start or skip mouse handling routines. This means that if you don’t have any OnMouse* functions in your code these routines will be skipped not wasting CPU cycles.

The thing is that depending on your setup these routines may be costly. When usesOnMouseEvents is true Unity does the following:

  1. Calls a method from C++ to C# which…
  2. For all cameras in your project checks if mouse cursor is within their rects;
  3. Uses camera.GetComponent<GUILayer>() in case there are IMGUI controls on screen and queries it if so;
  4. Does a 3D raycast;
  5. Does a 2D raycast;
  6. Performs a dance to figure out what OnMouse* messages to send;
  7. Sends messages using SendMessage (which is not fast);

Do you want this code running in your game every frame just because you find using OnMouseDown easier than working with touches and raycasting manually? Your choice.

You will probably be fine, as a matter of fact Input.simulateMouseWithTouches defaults to true. With that said however you should probably target using compiler directives(is this windows or is this a mobile device) and use the proper Input properties as this would allow you to be more future proof(deprecation of the simulation of mouse events with touch) and direct with using the appropriate input for a given device. This may not apply to your implementation and a single up to three touches may suit you just fine.

OnMouseDown() is like calling a RayCast in every object that has that method in it when you tap the screen. This is a lot of calculations when you have a lot of clickable objects. For instance: I am creating a tile based game that instantiates 64 tiles. If the Tile class had an OnMouseDown() method, the phone playing it would be doing calculations for 64 different rays. To avoid this I created a ClickableObject interface that has a Clicked() method. I then use a single class that casts one ray and if it hits a ClickableObject it calls the Clicked() method on that one object.