/// ---------------------------------------------
/// Ultimate Character Controller
/// Copyright (c) Opsive. All Rights Reserved.
/// https://www.opsive.com
/// ---------------------------------------------
namespace Opsive.UltimateCharacterController.Demo.Objects
{
using Opsive.Shared.Events;
using Opsive.UltimateCharacterController.Traits;
using UnityEngine;
///
/// A healing crate will update its material if it is healed.
///
public class HealingCrate : MonoBehaviour
{
[Tooltip("The material representing a damaged crate.")]
[SerializeField] protected Material m_DamagedMaterial;
[Tooltip("The material representing a healed crate.")]
[SerializeField] protected Material m_HealedMaterial;
[Tooltip("The crate is healed when the Health attribute is greater than the specified value.")]
[SerializeField] protected float m_HealedAttributeValue = 40;
private Renderer m_Renderer;
private Attribute m_HealthAttribute;
private float m_StartingAttributeValue;
///
/// Initialize the default values.
///
private void Awake()
{
m_Renderer = gameObject.GetComponent();
var attributeManager = gameObject.GetComponent();
m_HealthAttribute = attributeManager.GetAttribute("Health");
m_StartingAttributeValue = m_HealthAttribute.Value;
EventHandler.RegisterEvent(gameObject, "OnAttributeUpdateValue", OnUpdateValue);
}
///
/// The attribute value has beeen updated.
///
/// The attribute that has been updated.
private void OnUpdateValue(Attribute attribute)
{
if (attribute != m_HealthAttribute) {
return;
}
if (attribute.Value >= m_HealedAttributeValue) {
m_Renderer.sharedMaterial = m_HealedMaterial;
} else {
m_Renderer.sharedMaterial = m_DamagedMaterial;
}
}
///
/// Revert the health attribute value when the object is disabled.
///
private void OnDisable()
{
m_HealthAttribute.Value = m_StartingAttributeValue;
}
///
/// The object has been destroyed.
///
private void OnDestroy()
{
EventHandler.UnregisterEvent(gameObject, "OnAttributeUpdateValue", OnUpdateValue);
}
}
}