- Home /
Setting guiTexture to false works, but to true doesn't.
I'm trying to set a GUI texture to only show when my player health is at a specific value. The script is attached to the GUI object and accesses the player health scripts.
It seems to work setting it to false as it disappears when the player gets hit, but when the health goes back up it never re-activates (this is visible in both the game and hierarchy). Why is this?
Oh and here is the code:
void Start () {
health = GameObject.FindGameObjectWithTag("Player").GetComponent<Health>();
}
// Update is called once per frame
void Update () {
if (health.currentHealth == 7) gameObject.guiTexture.active = true;
if (health.currentHealth == 6) gameObject.guiTexture.active = false;
if (health.currentHealth == 5) gameObject.guiTexture.active = false;
if (health.currentHealth == 4) gameObject.guiTexture.active = false;
if (health.currentHealth == 3) gameObject.guiTexture.active = false;
if (health.currentHealth == 2) gameObject.guiTexture.active = false;
if (health.currentHealth == 1) gameObject.guiTexture.active = false;
}
}
Answer by Gruffy · Mar 20, 2014 at 09:00 PM
try .enabled instead of .active.
A guiTexture when added throughthe editor window in Unity is still a gameobject, this means using .active will result in you turning off the entire gameobject holding the GUiTexture..You want to merely disable the texture component of the GUITexture Transform.
your "if" conditional could be optimized a little too...to the below.. read it, it does the same thing as all the code above
if(health.currentHealth != 7)
{
gameObject.guiTexture.enabled = false;
}
else
{
gameObject.guiTexture.enabled = true;
}
It may turn out that you need to add ".texture" to the scope operator in the gameObject line of code...like so...
gameObject.giuTexture.texture.enabled
Anyway, lets start here and go forward.
Take care bud and thanks for reading. Gruffy
Thank you so much, such a simple thing but it usually is eh?
Thanks also for the extra help with optimization!
Answer by robertbu · Mar 20, 2014 at 09:01 PM
Switch from this:
gameObject.guiTexture.active = true;
To:
guiTexture.enabled = true;
You can rewrite your script above as:
void Update() {
guiTexture.enabled = (health.currentHelth == 7);
}
$$anonymous$$uch appreciated, this and the answer above fixed the problem.