How would I make this to use the new UI buttons instead of the OnGUI buttons?
function OnGUI () {
var guiTime = time;
var minutes : int = guiTime / 60; //Divide the guiTime by sixty to get the minutes.
var seconds : int = guiTime % 60;//Use the euclidean division for the seconds.
var fraction : int = (guiTime * 100) % 100;
textTime = String.Format ("{0:00}:{1:00}:{2:00}", minutes, seconds, fraction);
//text.Time is the time that will be displayed.
GetComponent(GUIText).text = textTime;
if (GUI.Button(Rect(500,55,50,30), buttonTexture, buttonText)){
timerOn = !timerOn;
if(timerOn) buttonText = "Stop";
else buttonText = "Start";
audio.PlayOneShot(beep1);
}
if (GUI.Button(Rect(555,55,50,30), buttonTexture, "Reset")){
time = 0;
audio.PlayOneShot(beep2);
}
}
I’ll try to tell you my approach, but it’s hard to explain only with words. Also, some information is missing (you obviously have more than 2 buttons, so I’ll assume you also have a Text object somewhere to display the actual time)
I’d make 2 scripts, one for each button.
For the Start/Stop button:
- Add a reference to the Text object that should display the formatted time.
- Add a public property to store the elapsed time.
- The lines where you create a string with the current time expressed as hh:mm:ss would be inside a “if (timerOn) { … }” block inside the Update method. After getting the string, instead of searchin for a GUIText component, use the Text object’s reference.
- The lines that change the state of the timer and the text on the button (“Stop” or “Start”) would be on a public method called “OnClick” or something like that.
- Set the “On Click” callback on the inspector to call the OnClick method.
For the Reset button:
- Add a reference to the Stop/Start button.
- Add an “OnClick” method that sets the StopStart’s elapsed time property to 0 and plays the sound.
- In the inspector, set the On Click for this button to that OnClick method.