OnTouch
From Unify Community Wiki
Adapted from OnMouseDown by User:Caue.rego, this Javascript sends `OnMouse` equivalent messages based on touch devices taps.
Attach the script to the camera that is rendering the clickable (tappable) objects.
Add a layer argument to the Raycast call if you need to avoid unnecessary intersections.
This is only for objects with colliders, not for `GUIText` and `GUITexture`.
Instead of calling `OnMouse` events, we use `OnPointer` (suggested name) to emphasize how we should avoid `OnMouse` due to performance warnings. (Though I've got no idea if that's just a legacy warning).
OnTouch.js
// Allows "OnMouse()" events to work on the mobile devices. // Attach this to the main camera. #pragma strict #pragma implicit #pragma downcast private var lastHitObject : GameObject; function Update () { var hit : RaycastHit; for (var i = 0; i < Input.touchCount; ++i) { // Construct a ray from the current touch coordinates var ray = camera.ScreenPointToRay(Input.GetTouch(i).position); if ( Physics.Raycast(ray, hit) ) { var hitObject = hit.transform.gameObject; if (Input.GetTouch(i).phase == TouchPhase.Began) { lastHitObject = hitObject; hitObject.SendMessage("OnPointerDown"); } if (Input.GetTouch(i).phase == TouchPhase.Ended) { if (lastHitObject == hitObject) { hitObject.SendMessage("OnPointerUpAsButton"); } hitObject.SendMessage("OnPointerUp"); lastHitObject = null; } } } }
Then, on whichever script you'd use OnMouse, use this instead:
// Usage instance #if UNITY_EDITOR or UNITY_STANDALONE or UNITY_WEBPLAYER function OnMouseUpAsButton () { OnPointerUpAsButton(); } #endif function OnPointerUpAsButton () { //whatever }