using NextMind.NeuroTags;
using UnityEngine;
using UnityEngine.UI;
///
/// This component makes the triangle feedback react to stimulation, by switching between to .
///
public class TriangleFeedbackStimulation : MonoBehaviour
{
///
/// The NeuroTag from which we get the stimulation values.
///
[SerializeField]
private NeuroTag neuroTag;
///
/// The material instantiated on the triangle.
///
[SerializeField]
private Material material = null;
///
/// The color applied in case of a stimulation value lower than 0.5.
///
[SerializeField]
private Color defaultColor = default;
///
/// The color applied in case of a stimulation value greater than 0.5.
///
[SerializeField]
private Color stimulatedColor = default;
///
/// Should we hide the triangle feedback when the linked NeuroTag becoms inactive?
///
[SerializeField]
private bool autoHideFeedback = default;
#region Unity methods
private void Awake()
{
if (neuroTag == null)
{
// Find the component in parents.
neuroTag = GetComponentInParent();
}
if (neuroTag != null)
{
neuroTag.onStimulationStateUpdated.AddListener(OnStimulationStateUpdated);
neuroTag.onBecameActivated.AddListener(OnNeuroTagActivationChanged);
neuroTag.onBecameDeactivated.AddListener(OnNeuroTagActivationChanged);
// Set initial state.
OnNeuroTagActivationChanged();
}
// Force to create an instance of the given material.
material = new Material(material);
SetMaterials();
}
private void OnDestroy()
{
if (neuroTag != null)
{
neuroTag.onStimulationStateUpdated.RemoveListener(OnStimulationStateUpdated);
neuroTag.onBecameActivated.RemoveListener(OnNeuroTagActivationChanged);
neuroTag.onBecameDeactivated.RemoveListener(OnNeuroTagActivationChanged);
}
}
#endregion
#region Event callbacks
///
/// Apply the right color regarding the stimulation value.
///
///
///
public void OnStimulationStateUpdated(GameObject target, float value)
{
material.color = (value > 0.5f) ? stimulatedColor : defaultColor;
}
///
/// Show the feedback when the NeuroTag becomes active, hide it otherwise.
///
private void OnNeuroTagActivationChanged()
{
if (autoHideFeedback)
{
SetVisible(neuroTag.IsVisible);
}
}
#endregion
///
/// Set the material on all the children.
///
private void SetMaterials()
{
for (int i = 0; i < transform.childCount; i++)
{
Transform t = transform.GetChild(i);
Renderer r = t.GetComponent();
if (r != null)
{
r.sharedMaterial = material;
}
else
{
Image image = t.GetComponent();
if (image != null)
{
image.material = material;
}
}
}
}
///
/// Show/Hide the sides of the triangle.
///
///
private void SetVisible(bool visible)
{
for (int i = 0; i < transform.childCount; i++)
{
transform.GetChild(i).gameObject.SetActive(visible);
}
}
}