Search code examples
androidbuttonunity-game-engineunityscriptcollider

Unity Collider Button is not working on Android


I have a problem with a collider button: when I use the button on PC it works fine, but when I use it on mobile device the script is not working (but the collider should make a fade effect).

Video showing desired effect.

This is the script I have:

#pragma strict

function OnMouseDown(){
    GameObject.FindWithTag("MainCamera").GetComponent(orbit).mainMenu = false;  
    for (var child : Transform in GameObject.Find("logo").transform) {
        child.gameObject.active = false;    
    }
    var enemy:GameObject[] = GameObject.FindGameObjectsWithTag("enemy");
    for (var child3 : GameObject in enemy) {
        Destroy(child3);
    }

    for (var child : Transform in GameObject.Find("menu_main").transform) {
        child.gameObject.active = false;    
    }   

    var num:GameObject[] = GameObject.FindGameObjectsWithTag("num");
    for (var child2 : GameObject in num) {
        Destroy(child2);
    }

    for (var child : Transform in GameObject.Find("menu_end").transform) {
        child.gameObject.active = false;    
    }   

    for (var child : Transform in GameObject.Find("healthbar").transform) {
        child.gameObject.active = true; 
    }   
    GameObject.Find("_Game").GetComponent(game).score = 0;  
}

Solution

  • So your issue boils down to something very simple. While touch events are similar to mouse events and in a lot of ways they are handled the same, but this is one of those cases where they're not.

    Simply put, OnMouseDown doesn't work on mobile.

    The answer there has an outdated link (and contains a typo), here's where it should point:

    http://wiki.unity3d.com/index.php/OnMouseDown

    And the relevant code (in JS / UnityScript, which you are using, although I do advise switching to C#, it's relatively painless):

    function Update () {
        // Code for OnMouseDown in the iPhone. Unquote to test.
        var hit : RaycastHit;
        for (var i = 0; i < Input.touchCount; ++i) {
            if (Input.GetTouch(i).phase == TouchPhase.Began) {
            // Construct a ray from the current touch coordinates
            var ray = camera.ScreenPointToRay (Input.GetTouch(i).position);
            if (Physics.Raycast (ray,hit)) {
                hit.transform.gameObject.SendMessage("OnMouseDown");
              }
           }
       }
    }
    

    Just attach a new script with this function in it to the main camera and you're good to go. Your existing OnMouseDown script will start working again.