Reputation:
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?
Upvotes: 0
Views: 1158
Reputation: 3212
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();
}
Upvotes: 1