Search code examples
c#unity-game-engineinputtouch

Unity. how can I get Touch by fingerID?


We have the index of the touches and method Input.GetTouch(int index) which returns Touch. Also we have fingerID property of Touch structure. How can we get a Touch by fingerID?


Solution

  • For getting a specific touch by ID you have to search for it in the existing touches.

    private static bool TryGetTouch(int fingerID, out Touch touch)
    {
        foreach(var t in Input.touches)
        {
            if(t.fingerID == fingerID)
            {
                touch = t;
                return true;
            }
        }
    
        // No touch with given ID exists
       touch = default;
       return false;
    }
    

    You can also use linq and do e.g.

    using System.Linq;
    
    ...
    
    private static bool TryGetTouch(int fingerID, out Touch touch)
    {
        try
        {
            touch = Input.touches.First(t => t.fingerID == fingerID);
            return true;
        }
        catch
        {
           // No touch with given ID exists
           touch = default;
           return false;
        }
    }
    

    and use it like

    if(TryGetTouch (someFingerID, out var touch))
    {
        // use touch here
    }
    else
    {
        // probably use a new touch and store its fingerID 
    }