- Home /
Changing GUI Text colour when health is low
Trying to get my GUI health text to change colour to red when it's below 40. Seen so many 'methods' of doing this, but can't get it to work. Here is my code:
using UnityEngine;
using System.Collections;
public class HealthController : MonoBehaviour
{
public static HealthController Instance { get; private set; }
public int health;
public GUIText healthTXT;
public GUIText healthTXT2;
public AudioClip shotSound;
public AudioClip dieSound;
public AnimationClip die;
public AnimationClip hit;
void Awake()
{
if (Instance == null)
{
Instance = this;
}
else
{
Destroy(gameObject);
}
}
void Start()
{
health = 100;
UpdateHealthText();
}
public void HasBeenAttacked20()
{
if (health <= 0) return;
health -= 20;
UpdateHealthText();
if (health <= 0) {
StartCoroutine(Die());
}
else
{
audio.PlayOneShot(shotSound);
animation.Play("hit");
}
}
public void HasBeenAttacked10()
{
if (health <= 0) return;
health -= 10;
UpdateHealthText();
if (health <= 0) {
StartCoroutine(Die());
}
else
{
audio.PlayOneShot(shotSound);
animation.Play("hit");
}
}
private void redText(){
if (health <= 40)
healthTXT.material.color = Color.red;
}
private void UpdateHealthText()
{
healthTXT.text = "LIFE: " + health.ToString();
healthTXT2.text = "LIFE: " + health.ToString();
}
private IEnumerator Die()
{
Motor.Instance.enabled = false;
GetComponent<CharacterAnimationController> ().enabled = false;
animation.Play("die");
audio.PlayOneShot(dieSound);
yield return new WaitForSeconds(die.length);
}
}
The redText() method is the one we're concerned with, I can't see why that doesn't work. Please let me know what I'm doing wrong and advise on an alternative solution. Please bear in mind that healthTXT2 is simply the shadow of healthTXT.
Thanks for your time and support in advance.
Answer by MrMatthias · Aug 28, 2014 at 01:35 PM
Do you actually call the redText method?
You're a star. I did try to call it before, but by you saying that I realised I didn't call it in both HasBeenAttacked10 and HasBeenAttacked20 methods. You sparked a brainwave. Thank you!
Your answer
Follow this Question
Related Questions
Changing two different objects renderer colour 1 Answer
Material doesn't have a color property '_Color' 4 Answers
Animating GUIText material properties 0 Answers
Assigning HDR color to material property via script 4 Answers
Distribute terrain in zones 3 Answers