Download examples/open_world_city/Assets/Scripts/HealthSystem.cs from ryzerrr/unity-game-agent: direct link, hf CLI and curl.
- Browser
- Download file 2.34 kB
-
https://huggingface.co/ryzerrr/unity-game-agent/resolve/main/examples/open_world_city/Assets/Scripts/HealthSystem.cs
- Command line
-
hf download hf://ryzerrr/unity-game-agent/examples/open_world_city/Assets/Scripts/HealthSystem.cs
-
curl -L -o HealthSystem.cs https://huggingface.co/ryzerrr/unity-game-agent/resolve/main/examples/open_world_city/Assets/Scripts/HealthSystem.cs
2.34 kB
| using UnityEngine; | |
| using UnityEngine.Events; | |
| namespace UnityAgent | |
| { | |
| /// <summary> | |
| /// Damageable entity with health regen and death event. Pairs with the | |
| /// optional <see cref="HealthBar"/> UI component. | |
| /// </summary> | |
| public class HealthSystem : MonoBehaviour | |
| { | |
| [] | |
| public float maxHealth = 100f; | |
| public float currentHealth { get; private set; } | |
| public float regenPerSecond = 1f; | |
| public float regenDelay = 5f; | |
| [] | |
| public UnityEvent onDeath; | |
| public UnityEvent<float> onDamaged; | |
| private float _lastDamageTime; | |
| private bool _dead; | |
| public float Normalised => currentHealth / maxHealth; | |
| private void Awake() | |
| { | |
| currentHealth = maxHealth; | |
| } | |
| private void Update() | |
| { | |
| if (_dead) return; | |
| if (Time.time - _lastDamageTime > regenDelay && currentHealth < maxHealth) | |
| { | |
| currentHealth = Mathf.Min(maxHealth, currentHealth + regenPerSecond * Time.deltaTime); | |
| } | |
| } | |
| public void TakeDamage(float amount) | |
| { | |
| if (_dead) return; | |
| currentHealth = Mathf.Max(0f, currentHealth - amount); | |
| _lastDamageTime = Time.time; | |
| onDamaged?.Invoke(amount); | |
| if (currentHealth <= 0f) Die(); | |
| } | |
| public void Heal(float amount) | |
| { | |
| if (_dead) return; | |
| currentHealth = Mathf.Min(maxHealth, currentHealth + amount); | |
| } | |
| private void Die() | |
| { | |
| _dead = true; | |
| onDeath?.Invoke(); | |
| Destroy(gameObject, 0.5f); | |
| } | |
| } | |
| /// <summary> | |
| /// Simple health bar that reads a <see cref="HealthSystem"/> and updates | |
| /// a child <c>Image.fillAmount</c>. | |
| /// </summary> | |
| public class HealthBar : MonoBehaviour | |
| { | |
| public HealthSystem source; | |
| public UnityEngine.UI.Image fillImage; | |
| public bool hideWhenFull = true; | |
| private void Update() | |
| { | |
| if (source == null || fillImage == null) return; | |
| float n = source.Normalised; | |
| fillImage.fillAmount = n; | |
| if (hideWhenFull) fillImage.transform.parent.gameObject.SetActive(n < 0.999f); | |
| } | |
| } | |
| } | |