Created
November 14, 2021 14:28
-
-
Save didacus/bd959448ddb55db98a52c6a26ce346bf to your computer and use it in GitHub Desktop.
Unity - Basic script to manage player health
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class PlayerHealthManager : MonoBehaviour | |
{ | |
public int startingHealth; | |
private int currentHealth; | |
public float flashLength; | |
private float flashCounter; | |
private Renderer renderColor; | |
private Color storedColor; | |
void Start() | |
{ | |
currentHealth = startingHealth; | |
// Get colours from gameObject | |
renderColor = GetComponent<Renderer>(); | |
storedColor = renderColor.material.GetColor("_Color"); | |
} | |
void Update() | |
{ | |
// Kill player if health runs out | |
if (currentHealth <= 0) | |
{ | |
gameObject.SetActive(false); | |
} | |
// Change colour back to original after certain time | |
if (flashCounter > 0) | |
{ | |
flashCounter -= Time.deltaTime; | |
if (flashCounter <= 0) | |
{ | |
renderColor.material.SetColor("_Color", storedColor); | |
} | |
} | |
} | |
// Apply player damage | |
public void DamagePlayer(int damage) | |
{ | |
currentHealth -= damage; // Apply damage | |
flashCounter = flashLength; // Set time for color change | |
renderColor.material.SetColor("_Color", Color.red); // Change color | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment