简体   繁体   中英

Unity - Input.GetMouseButtonDown

I created a script where by clicking on the smartphone display, an object was activated. I used Input.GetMouseButtonDown(0) to check if a tap was made on the display. The script works fine, but I have a problem: if I insert a button in the scene, clicking on the button I receive both the click of the button and that of the Input.GetMouseButtonDown function. How could I "divide" the two touches?

// Example
void Update()
{
    if (Input.GetMouseButtonDown(0))
    myObject.SetActive(true); 
}
            
public void PauseButton()
{
    // Open Pause Panel
            
}

I was thinking of deleting "Input.GetMouseButtonDown (0)" and using an invisible button and resizing it on the portion of the display I needed.

Add Tag to your UI button like: "UI"

Below function tells whether a click was Over a UI object tagged with a UI tag, so you can check in your screen tap function if you should fire your event or not

public static class InputHandler
{
    public const string CompareTagForUIElements = "UI";

    public static bool IsPointerOverUIObject(int touchId)
    {
        var eventDataCurrentPosition = new PointerEventData(EventSystem.current);
        // I'm using touch since you are talking about smartphones, 
        // if you still need click use Input.mousePosition
        eventDataCurrentPosition.position = new Vector2(GetTouch(touchId).position.x, GetTouch(touchId).position.y);
        List<RaycastResult> results = new List<RaycastResult>();
        EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
        for (int i = 0; i < results.Count; i++)
        {
            if (results[i].gameObject.CompareTag(CompareTagForUIElements))
                return true;
        }
        return false;
    }
}

So rather than

public void ITappedOnScreen()
{
    if(Input.GetMouseButtonDown(0))
        Debug.Log("Screen tapped");
}

use

public void ITappedOnScreen()
{
    if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Begin &&
        !InputHandler.IsPointerOverUIObject(0))
        Debug.Log("Screen tapped");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM