x


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;
       }
    }
}
more ▼

asked Aug 20 '12 at 02:18 AM

Ufando gravatar image

Ufando
20 1 4

Did that do the trick? Don't forget to mark the question as answered if it did.

Aug 20 '12 at 05:05 PM Khada
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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;
    }
}
more ▼

answered Aug 20 '12 at 07:29 AM

Khada gravatar image

Khada
2.2k 2 9

Yup that worked, i also needed to call the OnGui function in update and that got it working, thanks.

Aug 20 '12 at 09:18 PM Ufando

Oh, you shouldn't need to do that. You actually just need to rename the function from "OnGui" to "OnGUI".

Aug 21 '12 at 04:36 AM Khada
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x506
x475
x379

asked: Aug 20 '12 at 02:18 AM

Seen: 442 times

Last Updated: Aug 21 '12 at 04:36 AM