I'm creating a touch manager, which fires Began
and Ended
events and other monobehaviours
can subscribe to them. For some reason I am unable to find any information on creating a list of events actions.
This is an illustration of what I currently have:
public class TouchHandler : MonoBehaviour {
private static readonly int MAX_TOUCH_COUNT = 2;
public event Action<int> Began;
public event Action<int> Ended;
private void Update() {
if (Input.touchCount > 0) {
Touch[] touches = Input.touches;
int touchCount = Mathf.Min(touches.Length, MAX_TOUCH_COUNT);
for (int i = 0; i < touchCount; i++) {
Touch t = touches[i];
if (t.phase == TouchPhase.Began)
Began?.Invoke(i);
else if (t.phase == TouchPhase.Ended)
Ended?.Invoke(i);
}
}
}
}
public class Listener : MonoBehaviour {
[SerializeField] private TouchHandler th;
private int touchIndexToListen = 0;
private void OnEnable() {
th.Began += TouchBegan;
th.Ended += TouchEnded;
}
private void OnDisable() {
th.Began -= TouchBegan;
th.Ended -= TouchEnded;
}
private void TouchBegan(int index) {
if (index != touchIndexToListen)
return;
Debug.Log("TouchBegan");
}
private void TouchEnded(int index) {
if (index != touchIndexToListen)
return;
Debug.Log("TouchEnded");
}
}
This is how I'd want it to work:
public class TouchHandler : MonoBehaviour {
private static readonly int MAX_TOUCH_COUNT = 2;
public event Action[] Began = new Action[MAX_TOUCH_COUNT];
public event Action[] Ended = new Action[MAX_TOUCH_COUNT];
private void Update() {
if (Input.touchCount > 0) {
Touch[] touches = Input.touches;
int touchCount = Mathf.Min(touches.Length, MAX_TOUCH_COUNT);
for (int i = 0; i < touchCount; i++) {
Touch t = touches[i];
if (t.phase == TouchPhase.Began)
Began[i]?.Invoke();
else if (t.phase == TouchPhase.Ended)
Ended[i]?.Invoke();
}
}
}
}
public class Listener : MonoBehaviour {
[SerializeField] private TouchHandler th;
private int touchIndexToListen = 0;
private void OnEnable() {
th.Began[touchIndexToListen] += TouchBegan;
th.Ended[touchIndexToListen] += TouchEnded;
}
private void OnDisable() {
th.Began[touchIndexToListen] -= TouchBegan;
th.Ended[touchIndexToListen] -= TouchEnded;
}
private void TouchBegan(int index) {
Debug.Log("TouchBegan");
}
private void TouchEnded(int index) {
Debug.Log("TouchEnded");
}
}
So in short: I want to subscribe only to specific touch indexes, which also helps me get rid of the if (index != touchIndexToListen)
check in other monobehaviours
.
The reason I'm doing this touch manager is because I want a clean way to handle mouse input using the same class and I need to be able to fire the ended event when app is minimized in Android. I've left those parts out of this illustration, since they are irrelevant to this question.