Skip to content

Instantly share code, notes, and snippets.

@didacus
Created November 14, 2021 14:28
Show Gist options
  • Save didacus/bd959448ddb55db98a52c6a26ce346bf to your computer and use it in GitHub Desktop.
Save didacus/bd959448ddb55db98a52c6a26ce346bf to your computer and use it in GitHub Desktop.
Unity - Basic script to manage player health
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