Player Health

Checked with version: 4.6

-

Difficulty: Beginner

This is part 6 of 10 of the Survival Shooter tutorial, in which you will program the player's health, which is used in reference by other elements of the game.

Player Health

Beginner Survival Shooter tutorial

Transcripts

PlayerHealth

Code snippet

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class PlayerHealth : MonoBehaviour
{
    public int startingHealth = 100;                            // The amount of health the player starts the game with.
    public int currentHealth;                                   // The current health the player has.
    public Slider healthSlider;                                 // Reference to the UI's health bar.
    public Image damageImage;                                   // Reference to an image to flash on the screen on being hurt.
    public AudioClip deathClip;                                 // The audio clip to play when the player dies.
    public float flashSpeed = 5f;                               // The speed the damageImage will fade at.
    public Color flashColour = new Color(1f, 0f, 0f, 0.1f);     // The colour the damageImage is set to, to flash.


    Animator anim;                                              // Reference to the Animator component.
    AudioSource playerAudio;                                    // Reference to the AudioSource component.
    PlayerMovement playerMovement;                              // Reference to the player's movement.
    PlayerShooting playerShooting;                              // Reference to the PlayerShooting script.
    bool isDead;                                                // Whether the player is dead.
    bool damaged;                                               // True when the player gets damaged.


    void Awake ()
    {
        // Setting up the references.
        anim = GetComponent <Animator> ();
        playerAudio = GetComponent <AudioSource> ();
        playerMovement = GetComponent <PlayerMovement> ();
        playerShooting = GetComponentInChildren <PlayerShooting> ();

        // Set the initial health of the player.
        currentHealth = startingHealth;
    }


    void Update ()
    {
        // If the player has just been damaged...
        if(damaged)
        {
            // ... set the colour of the damageImage to the flash colour.
            damageImage.color = flashColour;
        }
        // Otherwise...
        else
        {
            // ... transition the colour back to clear.
            damageImage.color = Color.Lerp (damageImage.color, Color.clear, flashSpeed * Time.deltaTime);
        }

        // Reset the damaged flag.
        damaged = false;
    }


    public void TakeDamage (int amount)
    {
        // Set the damaged flag so the screen will flash.
        damaged = true;

        // Reduce the current health by the damage amount.
        currentHealth -= amount;

        // Set the health bar's value to the current health.
        healthSlider.value = currentHealth;

        // Play the hurt sound effect.
        playerAudio.Play ();

        // If the player has lost all it's health and the death flag hasn't been set yet...
        if(currentHealth <= 0 && !isDead)
        {
            // ... it should die.
            Death ();
        }
    }


    void Death ()
    {
        // Set the death flag so this function won't be called again.
        isDead = true;

        // Turn off any remaining shooting effects.
        playerShooting.DisableEffects ();

        // Tell the animator that the player is dead.
        anim.SetTrigger ("Die");

        // Set the audiosource to play the death clip and play it (this will stop the hurt sound from playing).
        playerAudio.clip = deathClip;
        playerAudio.Play ();

        // Turn off the movement and shooting scripts.
        playerMovement.enabled = false;
        playerShooting.enabled = false;
    }       
}
import UnityEngine.UI;
var startingHealth : int = 100;                             // The amount of health the player starts the game with.
var currentHealth : int;                                    // The current health the player has.
var healthSlider : Slider;                                  // Reference to the UI's health bar.
var damageImage : Image;                                    // Reference to an image to flash on the screen on being hurt.
var deathClip : AudioClip;                                  // The audio clip to play when the player dies.
var flashSpeed : float= 5f;                             // The speed the damageImage will fade at.
var flashColour : Color = new Color(1f, 0f, 0f, 0.1f);      // The colour the damageImage is set to, to flash.


private var anim : Animator;                                              // Reference to the Animator component.
private var playerAudio : AudioSource;                                    // Reference to the AudioSource component.
private var playerMovement : PlayerMovement;                              // Reference to the player's movement.
private var playerShooting : PlayerShooting;                              // Reference to the PlayerShooting script.
private var isDead : boolean;                                                // Whether the player is dead.
private var damaged : boolean;                                               // True when the player gets damaged.


function Awake ()
{
    // Setting up the references.
    anim = GetComponent (Animator);
    playerAudio = GetComponent (AudioSource);
    playerMovement = GetComponent (PlayerMovement);
    playerShooting = GetComponentInChildren (PlayerShooting);

    // Set the initial health of the player.
    currentHealth = startingHealth;
}


function Update ()
{
    // If the player has just been damaged...
    if(damaged)
    {
        // ... set the colour of the damageImage to the flash colour.
        damageImage.color = flashColour;
    }
    // Otherwise...
    else
    {
        // ... transition the colour back to clear.
        damageImage.color = Color.Lerp (damageImage.color, Color.clear, flashSpeed * Time.deltaTime);
    }

    // Reset the damaged flag.
    damaged = false;
}


public function TakeDamage (amount : int)
{
    // Set the damaged flag so the screen will flash.
    damaged = true;

    // Reduce the current health by the damage amount.
    currentHealth -= amount;

    // Set the health bar's value to the current health.
    healthSlider.value = currentHealth;

    // Play the hurt sound effect.
    playerAudio.Play ();

    // If the player has lost all it's health and the death flag hasn't been set yet...
    if(currentHealth <= 0 && !isDead)
    {
        // ... it should die.
        Death ();
    }
}


function Death ()
{
    // Set the death flag so this function won't be called again.
    isDead = true;

    // Turn off any remaining shooting effects.
    playerShooting.DisableEffects ();

    // Tell the animator that the player is dead.
    anim.SetTrigger ("Die");

    // Set the audiosource to play the death clip and play it (this will stop the hurt sound from playing).
    playerAudio.clip = deathClip;
    playerAudio.Play ();

    // Turn off the movement and shooting scripts.
    playerMovement.enabled = false;
    playerShooting.enabled = false;
}

EnemyAttack

Code snippet

using UnityEngine;
using System.Collections;


public class EnemyAttack : MonoBehaviour
{
    public float timeBetweenAttacks = 0.5f;     // The time in seconds between each attack.
    public int attackDamage = 10;               // The amount of health taken away per attack.


    Animator anim;                              // Reference to the animator component.
    GameObject player;                          // Reference to the player GameObject.
    PlayerHealth playerHealth;                  // Reference to the player's health.
    EnemyHealth enemyHealth;                    // Reference to this enemy's health.
    bool playerInRange;                         // Whether player is within the trigger collider and can be attacked.
    float timer;                                // Timer for counting up to the next attack.


    void Awake ()
    {
        // Setting up the references.
        player = GameObject.FindGameObjectWithTag ("Player");
        playerHealth = player.GetComponent <PlayerHealth> ();
        enemyHealth = GetComponent<EnemyHealth>();
        anim = GetComponent <Animator> ();
    }


    void OnTriggerEnter (Collider other)
    {
        // If the entering collider is the player...
        if(other.gameObject == player)
        {
            // ... the player is in range.
            playerInRange = true;
        }
    }


    void OnTriggerExit (Collider other)
    {
        // If the exiting collider is the player...
        if(other.gameObject == player)
        {
            // ... the player is no longer in range.
            playerInRange = false;
        }
    }


    void Update ()
    {
        // Add the time since Update was last called to the timer.
        timer += Time.deltaTime;

        // If the timer exceeds the time between attacks, the player is in range and this enemy is alive...
        if(timer >= timeBetweenAttacks && playerInRange && enemyHealth.currentHealth > 0)
        {
            // ... attack.
            Attack ();
        }

        // If the player has zero or less health...
        if(playerHealth.currentHealth <= 0)
        {
            // ... tell the animator the player is dead.
            anim.SetTrigger ("PlayerDead");
        }
    }


    void Attack ()
    {
        // Reset the timer.
        timer = 0f;

        // If the player has health to lose...
        if(playerHealth.currentHealth > 0)
        {
            // ... damage the player.
            playerHealth.TakeDamage (attackDamage);
        }
    }
}
var timeBetweenAttacks : float = 0.5f;     // The time in seconds between each attack.
var attackDamage : int = 10;               // The amount of health taken away per attack.


private var anim : Animator;                              // Reference to the animator component.
private var player : GameObject;                          // Reference to the player GameObject.
private var playerHealth : PlayerHealth;                  // Reference to the player's health.
private var enemyHealth : EnemyHealth;                    // Reference to this enemy's health.
private var playerInRange : boolean;                         // Whether player is within the trigger collider and can be attacked.
private var timer : float;                                // Timer for counting up to the next attack.


function Awake ()
{
    // Setting up the references.
    player = GameObject.FindGameObjectWithTag ("Player");
    playerHealth = player.GetComponent (PlayerHealth);
    enemyHealth = GetComponent(EnemyHealth);
    anim = GetComponent (Animator);
}


function OnTriggerEnter (other : Collider)
{
    // If the entering collider is the player...
    if(other.gameObject == player)
    {
        // ... the player is in range.
        playerInRange = true;
    }
}


function OnTriggerExit (other : Collider)
{
    // If the exiting collider is the player...
    if(other.gameObject == player)
    {
        // ... the player is no longer in range.
        playerInRange = false;
    }
}


function Update ()
{
    // Add the time since Update was last called to the timer.
    timer += Time.deltaTime;

    // If the timer exceeds the time between attacks, the player is in range and this enemy is alive...
    if(timer >= timeBetweenAttacks && playerInRange && enemyHealth.currentHealth > 0)
    {
        // ... attack.
        Attack ();
    }

    // If the player has zero or less health...
    if(playerHealth.currentHealth <= 0)
    {
        // ... tell the animator the player is dead.
        anim.SetTrigger ("PlayerDead");
    }
}


function Attack ()
{
    // Reset the timer.
    timer = 0f;

    // If the player has health to lose...
    if(playerHealth.currentHealth > 0)
    {
        // ... damage the player.
        playerHealth.TakeDamage (attackDamage);
    }
}

Related tutorials