How to stop a timer with GUI button?


The timer starts fine.

I’m trying to stop a timer using a GUI button

function OnGUI () {

	GUI.Label(new Rect(300, 100, 100, 20), (elapsedTime.ToString()));

	if (!hasBeenPressed)
           		//STOP TIMER HERE
                        stopTime = Time.time; //THESE LINES DON'T GET CALLED
                        timeActive = false;       //What am I doing wrong?

        if (hasBeenPressed) {



I started the timer in the update method when the jump button is fired.

I’m trying to stop it using a GUI button, which is posted above.

I have the following variables declared:

public var startTime : float; 
public var elapsedTime : float; 	
public var stopTime : float; 
public var timeActive : boolean; 

but I cannot figure out how to use them when the GUI button is fired.

My aim is to use the GUI button to stop the timer.

Any help or guidance in the right direction would be great.


Edit to add I need to get the stopTime so that I can pass it on later.
The timer is counting up from 0 when the jump button is fired.
The timer needs to stop when the GUI button is pushed - as seen in the code above.

So, in a nutshell.

Button A needs to start the counting up timer.
Button B needs to stop the counting up timer.

Your script doesn’t show the most crucial part … what is happening if !hasBeenPressed and before //STOP TIMER HERE ? This is the GUI.Button, yes? I posted links that should help with this, but you seem to just be asking for script to start and stop a timer with 2 buttons. This is easy :

 Update() {
      if (timeActive)
           elapsedTime += Time.deltaTime;

 GUI() {
      if (!timeActive) {
           GUI.Button(Start) {
                startTime = Time.time;
                timeActive = true;
      if (timeActive) {
           GUI.Button(Stop) {
                stopTime = Time.time;
                timeActive = false;

Also, my answer here works with GUI Buttons, it also has a boolean to change what GUI elements are shown : How to display data in an array - Questions & Answers - Unity Discussions