Day 19 Creating Player Health System and Health UI in Unity

Creating the Health Bar UI

Creating our Player Health System

Creating the Player’s health

[csharp]using UnityEngine;
using UnityEngine.UI;
public class PlayerHealth : MonoBehaviour
{
public Slider HealthBar;
public float Health = 100;
private float _currentHealth; void Start ()
{
_currentHealth = Health;
}
public void TakeDamage(float damage)
{
_currentHealth -= damage;
HealthBar.value = _currentHealth;
}
}
[/csharp]

Writing the Damage Dealing Code

[csharp highlight="57"]using UnityEngine;
using System.Collections;
public class EnemyAttack : MonoBehaviour
{
private Animator _animator;
private GameObject _player;
private bool _collidedWithPlayer;
void Awake()
{
_player = GameObject.FindGameObjectWithTag("Player");
_animator = GetComponent<Animator>();
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject == _player)
{
_animator.SetBool("IsNearPlayer", true);
}
print("enter trigger with _player");
}
void OnCollisionEnter(Collision other)
{
if (other.gameObject == _player)
{
_collidedWithPlayer = true;
}
print("enter collided with _player");
}
void OnCollisionExit(Collision other)
{
if (other.gameObject == _player)
{
_collidedWithPlayer = false;
}
print("exit collided with _player");
}
void OnTriggerExit(Collider other)
{
if (other.gameObject == _player)
{
_animator.SetBool("IsNearPlayer", false);
}
print("exit trigger with _player");
}
private void Attack()
{
if (_collidedWithPlayer)
{
_player.GetComponent<PlayerHealth>().TakeDamage(10);
}
}
}
[/csharp]

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store