How to do this in C#?

I’m working on a player health script for my in game player (just a cube, at the moment). However, I have run into a barrier.

// Update is called once per frame
	void Update () {
		if ( Input.GetKeyDown("h"))
		{
			ShowHealth();
		}
	}

When the key “h” is touched, I want “ShowHealth();” to happen. I tried:

void ShowHealth();
{
	// Show what I want to appear via GUI
}

But then I found out GUI functions must be called with “void OnGUI()”. But my question is how would I create a function, in C# of course, inside the GUI?

Any help is appreciated.

Hi,

If I’m understanding you correctly, I think you just need a little point-of-view change on event-driven design. The OnGUI() function will be triggered once (or more) per frame and the Update() also once per frame. You’re not going to be calling GUI drawing methods from the Update() routines. Instead, you want to have flags that can be set/modified by the Update() routines that determine what the GUI routines call:

You’ll have something that’ll look like this:

void Update()
{
   if(Input.GetKeyDown("h"))
   {
      mShowHealth = true;
   }
}
void OnGUI()
{
   if(mShowHealth)
   {
      GUI.Label(new Rect(0,0,100,100), playerObject.GetHealth());
   }
}

Oh, ok. Thanks

Noob question, but what is the m before the words for? Still learning C# here…

EDIT: But where would you define mShowHealth, if it is only set to true?

something thats actually commonly not used with C# but with C++: Hungarian notation

it just shows within the variable name, that the variable is a member variable (private variable)

Just make it a Boolean variable that is set to false.

bool ShowHealth = false;

??

I don’t get how I can have what I want in ShowHealth. Like the player’s health and all. Why can’t it just be an integer?

Sorry, but I am learning still, and don’t know much about code. Everybody has to start somewhere.

bool mShowHealth = false;

void Update()
{
   if(Input.GetKeyDown("h"))
   {
      mShowHealth = true;
   }
   else
   {
      mShowHealth = false;
   }
}
void OnGUI()
{
   if(mShowHealth)
   {
      GUI.Label(new Rect(0,0,100,100), playerObject.GetHealth());
   }
}