0

In a Scene in Unity3D, how can I make code react to an action only once every one second in a MonoBehaviour in the runloop?

  • Possible duplicate of [How to throttle the speed of an event without using Rx Framework](http://stackoverflow.com/questions/21400514/how-to-throttle-the-speed-of-an-event-without-using-rx-framework) – Eugene Podskal Mar 13 '16 at 12:56
  • `private DateTime _nextAllowedTime = DateTime.MinValue; public void YourMethod() { if (DateTime.Now < _nextAllowedTime) { return; } if (Input.GetMouseButtonUp(0)){ score++; _nextAllowedTime = DateTime.Now.AddSeconds(1); } }` – Corak Mar 13 '16 at 12:57
  • You use Invoke and InvokeRepeating for timers in Unity – Fattie Mar 13 '16 at 13:15
  • Possible duplicate of [Unity. Function call after a certain period of time](http://stackoverflow.com/questions/21598444/unity-function-call-after-a-certain-period-of-time) – Fattie Mar 19 '16 at 19:23

1 Answers1

1

If you're in a Unity3D environment, stop reading and look at Joe Blow's answer. Otherwise, continue reading.


You could use a Stopwatch to time your events. Create one Stopwatch as a private field/property and initialize it from your constructor:

public YourClass()
{
    ScoreStopwatch = new Stopwatch();
    ScoreStopwatch.Start();
    // Other initialization...
}

private Stopwatch ScoreStopwatch { get; set; }

Then you can use the Elapsed property to get the time since your last score increase, like this:

if(Input.GetMouseButtonUp(0) && ScoreStopwatch.Elapsed.TotalSeconds > 1)
{
    score++;
    ScoreStopwatch.Reset();
    ScoreStopwatch.Start();
}
Community
  • 1
  • 1
Gediminas Masaitis
  • 3,172
  • 14
  • 35
  • I'm getting error: ``Type `System.Diagnostics.Stopwatch' does not contain a definition for `Restart' and no extension method `Restart' of type `System.Diagnostics.Stopwatch' could be found (are you missing a using directive or an assembly reference?)`` –  Mar 13 '16 at 13:00
  • @Brown Ah, that would be because [`Stopwatch.Restart`](https://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.restart(v=vs.110).aspx) was only added in .NET 4.0, you must be using an older version. I updated my code to not use any new methods. – Gediminas Masaitis Mar 13 '16 at 13:03
  • What .Net Version are you using? Seems like [Restart](https://msdn.microsoft.com/de-de/library/system.diagnostics.stopwatch.restart.aspx) is available since 4.0. – Corak Mar 13 '16 at 13:03
  • @GediminasMasaitis - you would really never use "Stopwatch" for this. It's totally inappropriate in a frame-based environment. Note that this is unity3D question - often a source of confusion – Fattie Mar 13 '16 at 13:17
  • @JoeBlow *sigh*, once again people forget to include relevant information in the title/question, and I forget to look at the tags. Do you suppose I should delete the answer? – Gediminas Masaitis Mar 13 '16 at 13:25