How to detect a touch on a game object

I am developing a game on Unity for iOS devices. I applied the following code to touch:

void Update () {
    ApplyForce ();
}

void ApplyForce() {

    if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) {
        Debug.Log("Touch Occured");     
    }
}

I dragged this script onto my game object, which is a sphere. But the log message appears no matter where I touch. I want to detect touch only when users touch the object.

+4
source share
2 answers

- , , . , . , , , .

void Update () {
    if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) 
    {
        Ray ray = Camera.main.ScreenPointToRay( Input.GetTouch(0).position );
        RaycastHit hit;

        if ( Physics.Raycast(ray, out hit) && hit.transform.gameObject.Name == "myGameObjectName")
        {
            hit.GetComponent<TouchObjectScript>().ApplyForce();  
        }
    }
}

script, hit.transform.gameObject.Name == "myGameObjectName" , , , raycast, , . - , .

, , - , raycast ( ) . , - , .

script ( TouchObjectScript.cs)

void Update () {
}

public void ApplyForce() {

        Debug.Log("Touch Occured");   
}

- , , .

+16

: :

void OnMouseDown () {}

, . , 2 .

+2

Source: https://habr.com/ru/post/1524095/


All Articles