Advertisement
Guest User

HealthLogic.cs

a guest
Aug 22nd, 2014
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.37 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class HealthLogic : MonoBehaviour {
  5.  
  6.     // Debugging
  7.     public bool loggingEnabled = false;
  8.  
  9.     // Stats
  10.     public float health = 10;
  11.     public float maxHealth = 10;
  12.     public float invulnerabilityPeriod = 0.2f;
  13.     [Range(0.0f,1.0f)] public float invulnOpacity = 0.5f;
  14.  
  15.     // Other
  16.     public bool playsSoundOnHit = false;
  17.  
  18.     private float oldOpacity;
  19.     private float invulnTime = 0;
  20.  
  21.     // Initialization
  22.     void Start ()
  23.     {
  24.         oldOpacity = this.renderer.material.color.a;
  25.     }
  26.  
  27.     void LateUpdate ()
  28.     {
  29.         if (loggingEnabled)
  30.             Debug.Log (health);
  31.     }
  32.  
  33.     public bool Damage (float amount)
  34.     {
  35.         if (Time.time > invulnTime)
  36.         {
  37.             health -= amount;
  38.             invulnTime = Time.time + invulnerabilityPeriod;
  39.  
  40.             if (playsSoundOnHit)
  41.                 audio.Play ();
  42.  
  43.             if (health <= 0)
  44.             {
  45.                 if (this.tag == "Player")
  46.                     Application.LoadLevel (0);
  47.                 else
  48.                     Destroy (gameObject);
  49.             }
  50.             else
  51.             {
  52.                 Color color = this.renderer.material.color;
  53.                 color.a = invulnOpacity;
  54.                 this.renderer.material.color = color;
  55.  
  56.                 StartCoroutine (normalizeOpacity (invulnerabilityPeriod));
  57.             }
  58.         }
  59.         return false;
  60.     }
  61.  
  62.     private IEnumerator normalizeOpacity (float delay)
  63.     {
  64.         yield return new WaitForSeconds (delay);
  65.  
  66.         Color color = this.renderer.material.color;
  67.         color.a = oldOpacity;
  68.         this.renderer.material.color = color;
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement