Help

Hey Guys,

How do you display and change the score when the player clicks a GUI button? I would like to add 5pts every time a specific button is pressed and display that to the player.

	if (GUI.Button (Rect (20,150,150,20)

Please Help thanks

var score = 0;

function OnGUI()
	{
	if (GUI.Button (Rect (20,150,150,20)))
		{
		score += 5;
		}
	}

That should do it

It depends on how you have your score set up, but here’s the simplest implementation.

Javascript:

var score:int = 0;
function OnGUI () {
	if (GUI.Button (Rect (20,150,150,20))) score++;
}

C#:

int score = 0;
void OnGUI () {
	if (GUI.Button (Rect (20,150,150,20))) score++;
}

I’m going to try it right now thanks guys.

@ beck i’m coding it in Java.

Question guys, now that I have it counting on button press, how would I display it in the GUI.text?

var score:int = 0;
var ScoreTEXT : guiText;

function Update() {
ScoreTEXT.text = Score .ToString();
}

function OnGUI () {
	if (GUI.Button (Rect (20,150,150,20))) score++;
}

I think that is it. It’s untested. But it should work. Tell me if there are any errors and I will be happy to fix them. :slight_smile:

Use

GUI.Label( Rect, String )

Rect = the rect your text will be in
String = the score as a String

I don’t remember now if Unity will throw an error for using an int where the String should be, but if it does, just add an empty String to the score and Unity will think it’s a String. Like this:

GUI.Label( scoreRect, score + "" );

If you have a custom skin, you can pass it as a 3rd parameter to the GUI.Label function.

I forgot about the ToString() method. It’s better :slight_smile:
My way is much more like a workaround.

I keep getting this error : The name ‘guiText’ does not denote a valid type (‘not found’). did you mean 'UnityEngine.GUIText?

Yep. lol

var score:int = 0;
var ScoreTEXT : GUIText;

function Update() {
ScoreTEXT.text = Score .ToString();
}

function OnGUI () {
	if (GUI.Button (Rect (20,150,150,20))) score++;
}

Fixed!

Hey Carking I now get the error “Unknown Identifier: Score” is that placeholder for me to put a number in?