using UnityEngine;
namespace NextMind.NeuroTags
{
///
/// A simple component forwarding the last confidence values of a to the attached to it.
///
/// If the is not referenced, this component will be disabled.
[RequireComponent(typeof(Animator))]
public class NeuroTagFeedback : MonoBehaviour
{
///
/// The NeuroTag from which we monitor the confidence.
///
/// If empty, the first NeuroTag found in parents will be used.
[SerializeField]
private NeuroTag neuroTag = null;
///
/// Should the feedback use the raw value received or should it rather be smoothed ?
///
[SerializeField]
private bool interpolateConfidenceValue = true;
///
/// The speed of interpolation in case we interpolate the confidence value.
///
[SerializeField]
private float confidenceSmoothingSpeed = 5;
///
/// The animator on which the confidence values will be forwarded.
///
protected Animator animator;
///
/// The current value.
///
private float currentConfidenceValue = 0;
///
/// The targeted value.
///
private float targetConfidenceValue = 0;
///
/// The name of the float parameter in the animator.
///
private const string confidenceParameterName = "ConfidenceValue";
#region Unity Methods
private void Awake()
{
// Find the animator component on this GameObject instance.
animator = GetComponent();
if (neuroTag == null)
{
// Find the NeuroTag component in parents
neuroTag = GetComponentInParent();
}
if (neuroTag != null)
{
neuroTag.onConfidenceChanged.AddListener(OnConfidenceUpdated);
}
}
private void Update()
{
HandleConfidenceUpdate();
}
private void OnDestroy()
{
if (neuroTag != null)
{
neuroTag.onConfidenceChanged.RemoveListener(OnConfidenceUpdated);
}
}
private void OnEnable()
{
// Disable this component if no NeuroTag is found.
if (neuroTag == null)
{
Debug.LogWarning("This feedback must be linked to a NeuroTag.", this);
this.enabled = false;
}
}
#endregion
///
/// Interpolate the confidence value and forward it to the animator.
///
private void HandleConfidenceUpdate()
{
if (interpolateConfidenceValue)
{
currentConfidenceValue = Mathf.Lerp(currentConfidenceValue, targetConfidenceValue, confidenceSmoothingSpeed * Time.deltaTime);
}
else
{
currentConfidenceValue = targetConfidenceValue;
}
animator.SetFloat(confidenceParameterName, currentConfidenceValue);
}
///
/// Update the targeted value.
///
private void OnConfidenceUpdated(float value)
{
targetConfidenceValue = value;
}
}
}