- Home /
How to change a guiTexture color when a float is a certain number?
If my question was a bit vague i'll expand here;
Basically what i want to do is have a little icon of a stomach (To represent hunger) and every frame have a variable that contains the hunger decrease by 0.1. Once the hunger level reaches certain intervals, i want the color to change on the guiTexure, for example; at 500.0f color = yellow at 250.0f color = red
I'm fairly new to scripting in unity, so i could be way off with this code, so can somebody please help me
It will decrease the CurrentHunger variable, however the colors do not change at the intervals.
Here's my code;
using UnityEngine;
using System.Collections;
public class Hunger : MonoBehaviour
{
public float CurrentHunger = 1000.0f;
public float MaxHunger = 1000.0f;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
CurrentHunger -= 0.1f;
if (CurrentHunger > MaxHunger)
{
CurrentHunger = MaxHunger;
}
}
void OnGui ()
{
if (CurrentHunger == 500.0f)
{
guiTexture.color = Color.yellow;
}
else if (CurrentHunger == 250.0f)
{
guiTexture.color = Color.red;
}
}
}
Did that do the trick? Don't forget to mark the question as answered if it did.
Answer by Khada · Aug 20, 2012 at 07:29 AM
A line like this:
if (CurrentHunger == 500.0f)
is actually testing whether or not x.xxxxxxxxx is exactly equal to 500.0000000 which is a bad way to do things. Even if your logic makes it clear that the if statement should trigger at some point, floating point numbers are not 100% accurate, and so still may not end up exactly the value you expect.
instead, use less-than and greater-than checks:
void OnGui ()
{
if (CurrentHunger < 250.0f)
{
guiTexture.color = Color.red;
}
else if (CurrentHunger < 500.0f)
{
guiTexture.color = Color.yellow;
}
}
Yup that worked, i also needed to call the OnGui function in update and that got it working, thanks.
Oh, you shouldn't need to do that. You actually just need to rename the function from "OnGui" to "OnGUI".
Your answer
![](https://koobas.hobune.stream/wayback/20220613075912im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
changing the color of particles using the legacy particle animator? 2 Answers
Solid color flash entire screen 2 Answers
Disco like GUITexture? 1 Answer
Changing two different objects renderer colour 1 Answer
gui.label color change 1 Answer