how do you count up with Repeat button?

So I’m using Javascript and I have been able to make a GUI button constantly spit out zeros in the console using the RepeatButton.
But I really just want it to count up

What am I doing wrong?

and how would change the counting to use GUI Text instead of straight to the console?

Thank You!

#pragma strict
function OnGUI () {
    var counter: int = 0;  
    GUI.Box (Rect (20,20,100,90), "Hold IT");
    if (GUI.RepeatButton (Rect (20,40,80,20), "press")) {
	Debug.Log(counter++);
  }
}

1 Answer

1

You need to take the variable out of the function, and declare it as class variable:

#pragma strict

var counter: int = 0; 

function OnGUI () {   
    GUI.Box (Rect (20,20,100,90), "Hold IT");
    if (GUI.RepeatButton (Rect (20,40,80,20), "press")) {
    Debug.Log(counter++);
  }
}

Otherwise the counter is set to 0 every time the GUI draws.

As for GUIText, add a GUIText component to the object, either through editor or by using AddComponent in script. If you add it in editor you can use GetComponent (in something like Start function, since you need to do that once). End then modify the text:

#pragma strict

var counter: int = 0; 
var guiText : GUIText;

function Start() {
   guiText = gameObject.GetComponent(GUIText);
}

function OnGUI () {   
    GUI.Box (Rect (20,20,100,90), "Hold IT");
    if (GUI.RepeatButton (Rect (20,40,80,20), "press")) {
       counter++;
       guiText.text = counter;
  }
}

I get an error saying Cannot convert int to string.

Convet the counter value to string, I think it's something like: guiText.text = counter.ToString();