For example, you can see that I'm using new List<> to reset touches in this code. I could use Clear instead, but then I'd have to have touches previously constructed, which is clutter. However, I'll do that kind of thing if it is better practice for memory allocation.
For fingerIDs, I don't even need to reconstruct the list every time, or even clear it. Again, I just put it where I did to not have to construct it earlier. I assume your answer to my question will answer the other question of how bad it is to do this, but feel free to specifically comment on that, and if you think it's worth checking to see if it's null before reconstructing it.
using UnityEngine;
using System.Collections.Generic;
public enum PressState
{
Unpressed,
Held,
Activated
}
public class Button
{
public PressState pressState;
public Rect rect;
List <int> fingerIDs;
public void Update ()
{
if (pressState == PressState.Unpressed)
{
fingerIDs = new List<int>();
for (int i = 0; i < Input.touchCount; ++i)
{
Touch touch = Input.GetTouch(i);
if (touch.phase == TouchPhase.Began && rect.Contains(touch.position))
{
pressState = PressState.Held;
fingerIDs.Add(touch.fingerId);
}
}
}
else if (pressState == PressState.Held)
{
List<Touch> touches = new List<Touch>();
for (int i = 0; i < Input.touchCount; ++i)
touches.Add(Input.GetTouch(i));
// Activate if holding finger(s) left the screen.
// Can be overridden in the next loop,
// if other fingers are touching the button.
// It won't be activated if some fingers left and
// others just slid elsewhere.
for (int i = 0; i < touches.Count; ++i)
{
if (fingerIDs.Contains(touches*.fingerId))*
_fingerIDs.Remove(touches*.fingerId);*_
_*}*_
_*if (fingerIDs.Count > 0)*_
_*{*_
_*pressState = PressState.Activated;*_
_*fingerIDs.Clear();*_
_*}*_
_*// After it's pressed, allow any other fingers to keep it held,*_
_*// no matter what they were doing before touching the button.*_
_*for (int i = 0; i < touches.Count; ++i)*_
<em><em>if (rect.Contains(touches_.position)) fingerIDs.Add(touches*.fingerId);*_</em></em>
<em><em>_*if (fingerIDs.Count > 0) pressState = PressState.Held;*_</em></em>
<em><em>_*else if (pressState != PressState.Activated) pressState = PressState.Unpressed;*_</em></em>
<em><em>_*}*_</em></em>
<em><em>_*// After activation.*_</em></em>
<em><em>_*else pressState = PressState.Unpressed;*_</em></em>
<em><em>_*}*_</em></em>
<em><em>_*}*_</em></em>
<em><em>_*```*_</em></em>