Monday, May 2, 2016

Touches/Taps On Objects In Mobile Games in Unity

Here's a script that will allow you to do something when you tap on a GameObject for mobile games in Unity. You could use OnMouseDown() and it would work, but after reading the Unity Reference and multiple forum posts it seems that this method is more efficient for mobile processors.

#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WEBGL
 void OnMouseDown() {
  //Code to execute when you click the object when the game is run on a non-mobile platform
 }

#elif UNITY_ANDROID || UNITY_IOS
void Update() {
    for(int i = 0; i<Input.touchCount; i++) {
        Ray ray = Camera.main.ScreenPointToRay (Input.GetTouch (i).position);
        RaycastHit hit;
        if(Input.GetTouch(i).phase == TouchPhase.Began) {
            if(Physics.Raycast(ray, out hit)) {
                //Code to execute when you touch the object when the game is run on a mobile platform (use hit.transform.gameObject or hit.collider.gameObject to refer to the GameObject that you touched)
            }
        }
    }
}
#endif

The way the code works is that if you run your game on a mobile device it will use Raycasting to determine when you touch the object and when you run your game on a non-mobile device it will use OnMouseDown() to determine when you click on the object. It is important to note that in order for Raycasting to work your object must have a 3D collider on it (ie. a BoxCollider instead of a BoxCollider2D). For more information on Raycasting you can look at Physics.Raycast in the Unity Reference.

-Reposted from Piazza

No comments:

Post a Comment