Try Get Touch Position

    0

    0

    UnityUnityUI

    Library: Unity

    using System.Collections.Generic;
    using System.Threading.Tasks;
    using UnityEngine;
    using UnityEngine.EventSystems;
    using UnityEngine.UI;
    // ReSharper disable Unity.PerformanceCriticalCodeNullComparison
    
    public class TryGetTouchPosition : MonoBehaviour
    {
      private readonly List<GraphicRaycaster> _graphicRaycasters = new();
    
      private async void Awake()
      {
        await Task.Yield(); //wait for Destroy()
    
        var canvases = FindObjectsOfType<Canvas>(true);
        foreach (var canvas in canvases) _graphicRaycasters.Add(canvas.GetComponent<GraphicRaycaster>());
      }
    
      public bool Try(out Vector2 touchPosition)
      {
        if (Input.GetMouseButton(0))
        {
          if (!IsPointerOverUIObject())
          {
            touchPosition = Input.mousePosition;
            return true;
          }
        }
    
        touchPosition = default;
        return false;
      }
    
      public bool TryOnce(out Vector2 touchPosition)
      {
        if (Input.GetMouseButtonDown(0))
        {
          if (!IsPointerOverUIObject())
          {
            touchPosition = Input.mousePosition;
            return true;
          }
        }
    
        touchPosition = default;
        return false;
      }
    
      private bool IsPointerOverUIObject()
      {
        var eventDataCurrentPosition = new PointerEventData(EventSystem.current) {position = Input.mousePosition};
        var results = new List<RaycastResult>();
    
        foreach (var graphicRaycaster in _graphicRaycasters)
        {
          var res = new List<RaycastResult>();
          if (graphicRaycaster != null) graphicRaycaster.Raycast(eventDataCurrentPosition, res);
          results.AddRange(res);
        }
    
        return results.Count > 0;
      }
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    Legal
    • Security
    • Privacy Policy
    • Code Privacy
    • Terms of Service
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.