using System;
using System.Collections.Generic;
using UnityEngine;
namespace NWH.Common.Input
{
///
/// Base class from which all input providers inherit.
///
public abstract class InputProvider : MonoBehaviour
{
///
/// List of all InputProviders in the scene.
///
public static List Instances = new List();
protected static int InstanceCount;
public virtual void Awake()
{
Instances.Add(this);
InstanceCount++;
}
public virtual void OnDestroy()
{
// Reset instances list on scene exit.
Instances.Remove(this);
InstanceCount--;
}
///
/// Returns combined input of all InputProviders present in the scene.
/// Result will be a sum of all inputs of the selected type.
/// T is a type of InputProvider that the input will be retrieved from.
///
public static int CombinedInput(Func selector) where T : InputProvider
{
int sum = 0;
for (int i = 0; i < InstanceCount; i++)
{
InputProvider ip = Instances[i];
if (ip is T provider)
{
sum += selector(provider);
}
}
return sum;
}
///
/// Returns combined input of all InputProviders present in the scene.
/// Result will be a sum of all inputs of the selected type.
/// T is a type of InputProvider that the input will be retrieved from.
///
public static float CombinedInput(Func selector) where T : InputProvider
{
float sum = 0;
for (int i = 0; i < InstanceCount; i++)
{
InputProvider ip = Instances[i];
if (ip is T provider)
{
sum += selector(provider);
}
}
return sum;
}
///
/// Returns combined input of all InputProviders present in the scene.
/// Result will be positive if any InputProvider has the selected input set to true.
/// T is a type of InputProvider that the input will be retrieved from.
///
public static bool CombinedInput(Func selector) where T : InputProvider
{
for (int i = 0; i < InstanceCount; i++)
{
InputProvider ip = Instances[i];
if (ip is T provider && selector(provider))
{
return true;
}
}
return false;
}
///
/// Returns combined input of all InputProviders present in the scene.
/// Result will be a sum of all inputs of the selected type.
/// T is a type of InputProvider that the input will be retrieved from.
///
public static Vector2 CombinedInput(Func selector) where T : InputProvider
{
Vector2 sum = Vector2.zero;
for (int i = 0; i < InstanceCount; i++)
{
InputProvider ip = Instances[i];
if (ip is T provider)
{
sum += selector(provider);
}
}
return sum;
}
}
}