Unity automatically clicks the Canvas
foreword
When encountering an item that does not require a mouse, you can use the following methods to directly trigger UI button events
source code
Pressing Q
can trigger the button event at the corresponding position under the UI
Tip: It needs to be mounted on a device with
GraphicRaycaster
componentsCanvas
public class TestClickCanvas: MonoBehaviour
{
GraphicRaycaster raycaster;
void Start()
{
raycaster = GetComponent<GraphicRaycaster> ();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Q))
{
PointerEventData pointerData = new PointerEventData(EventSystem.current);
List<RaycastResult> results = new List<RaycastResult>();
//想要点击的位置
pointerData.position = new Vector2(0,1080);
raycaster.Raycast(pointerData, results);
foreach (RaycastResult result in results)
{
Debug.Log("Hit " + result.gameObject.name);
if (result.gameObject.GetComponent<Button>()!=null)
{
//触发事件
result.gameObject.GetComponent<Button>().onClick.Invoke();
}
}
}
}
}
grateful
Detecting clicks on canvas https://answers.unity.com/questions/1526663/detect-click-on-canvas.html