Instantly share code, notes, and snippets.

@jweimann /NPC.cs
Last active Dec 29, 2016

Embed
What would you like to do?
using System;
using UnityEngine;
public class NPC : MonoBehaviour
{
[SerializeField]
private int _startingHp = 100;
[SerializeField]
private UnityEngine.UI.Slider _hpBarSlider;
private int _currentHp;
private void Start()
{
_currentHp = _startingHp;
}
internal void TakeDamage(int amount)
{
if (amount <= 0)
throw new ArgumentOutOfRangeException("Invalid Damage amount specified: " + amount);
_currentHp -= amount;
UpdateUI();
if (_currentHp <= 0)
Die();
}
private void UpdateUI()
{
var currentHpPct = (float)_currentHp / (float)_startingHp;
_hpBarSlider.value = currentHpPct;
}
private void Die()
{
GameObject.Destroy(this.gameObject);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment