1

I have a method that shows a window and then returns the value of the button clicked. What I have done is that when I click the button I change a variable and then the variable will be returned. What I need is someway to pause the method until the variable has been changed.

I program a game in unity and it's using mono.

Code:

public virtual Buttons Execute(){

        this.holder.SetActive(true); //Set the window active

        // Here wait for the user to click a button

        return clicked;//Returns the button clicked.
    }
Olof
  • 776
  • 2
  • 14
  • 33
  • It's not clear what you mean. When you set the value of a variable, it's changed immediately. What do you need to wait for? Can you show code which replicates the issue and explain what isn't working? – David Jun 21 '15 at 14:41
  • You might want to take a look at http://stackoverflow.com/questions/14189995/create-an-event-to-watch-for-a-change-of-variable – Jay Bosamiya Jun 21 '15 at 14:43
  • @David the problem is I need to know how you paus the method until the variable has changed value since I don't know if it will be seconds or minutes until that happens.. – Olof Jun 21 '15 at 14:47
  • @Olof: You shouldn't have to "pause the code" to wait for an event to take place. There should be other code which responds to the event when it happens. It's not really clear from the code you've shown how exactly that should happen in this case, but you should be responding to the button click rather than waiting for it. – David Jun 21 '15 at 14:51

1 Answers1

0

The code that handles the user interface is event driven, so the sensible thing to do would be to use an event instead of using a method like you try to do.

It's possible to create a method that works that way, but you have to create your own message pump that runs while you are waiting:

public virtual Buttons Execute(){

    this.holder.SetActive(true); // Set the window active

    clicked = null; // Set the state as undetermined

    while (clicked == null) { // Wait until it is set

      Application.DoEvents(); // Process messages
      Thread.Sleep(10); // Wait for a while

    }

    return clicked; // Returns the button clicked.
}

You can read in the question Use of Application.DoEvents() for explanations of the pitfalls of using DoEvents this way.

Community
  • 1
  • 1
Guffa
  • 687,336
  • 108
  • 737
  • 1,005