- Home /
Screen.width ~ HealthBar problem - C#
I've spent over an hour setting up the GUI.Box in C# for a "healthbar" and even though the code compiles, it seems the logic of the script seems to be correct, the "healthbar" wont show up when playtested and the float value healthBarLength shows up as 0 inside the unity editor. I wanted it to work the following way: GUI.Box is 1/2 of the screenwidth, it becomes shorter when you lose health... It shows nothing when you drag. Also, where should I place the Float healthBarLength for the script to work, if I put it just next to
public int curHealth = 100; public float healthBarLength = (curHealth / maxHealth);
It wont compile at all ;/
using UnityEngine;
using System.Collections;
public class healthbar : MonoBehaviour {
public int maxHealth = 100;
public int curHealth = 100;
public float healthBarLength;
// Use this for initialization
void Start () {
OnGui();
}
// Update is called once per frame
void Update () {
}
void OnGui()
{
healthBarLength = ((Screen.width / 2) / (curHealth / maxHealth));
GUI.Box(new Rect(100, 100, healthBarLength, 20), curHealth + "/" + maxHealth);
}
}
Answer by appearance · Feb 06, 2013 at 01:17 PM
You are doing two mistakes here. First, rename the method from
void OnGui() {}
to
void OnGUI () {}
Method name is case-sensitive.
Second, you should not call OnGUI() from within Start() function. OnGUI() will be called automatically/repeatedly by unity.
Thanks for the pointer, I fixed the "()", but it had no affect on the GUI display :(
Not the (), the upper/lowercase of the function name. Your "OnGui" will never be called.
Oh $$anonymous$$y upper case GOD, haven't noticed that, that has been the case all the time, Thanks for the help!!
Answer by LukeAntConroy · Feb 06, 2013 at 01:43 PM
using UnityEngine; using System.Collections;
public class PlayerGUI : MonoBehaviour {
public int maxHealth = 100;
public int curHealth = 100;
public float healthBarLength;
// Use this for initialization void Start () { //OnGUI(); }
// Update is called once per frame void Update () {
}
void OnGUI() { healthBarLength = ((Screen.width / 2) / (curHealth / maxHealth)); GUI.Box(new Rect(100, 100, healthBarLength, 20), curHealth + "/" + maxHealth);
} }
I ran your code seems to work fine on mine but just to let you know you don't need to have OnGUI in the Start function as OnGUI will update automatically
I don't know why but the GUI.Box will not appear in the gameplay mode :/, no matter if it is in the Start () function, or alone
Is the script attached to camera or a game object ?
Yes, I attached in to the firstperson character controller, did not work, so I dragged it on the camera, no difference either
As Wolfram said do you have it as OnGui if so change it to OnGUI ,either from that I can't see why it is not working.