How to run some code in Unity3D after every x seconds?
unity-game-engine
Solution
Actually, there's a better way than using a coroutine with yield. InvokeRepeating method has less overhead and doesn't need the ugly while(true) construct:
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
public Rigidbody projectile;
public bool Condition;
void LaunchProjectile() {
if (!Condition) return;
Rigidbody instance = Instantiate(projectile);
instance.velocity = Random.insideUnitSphere * 5;
}
void Start() {
InvokeRepeating("LaunchProjectile", 2, 0.3F);
}
}
Also, how is your condition defined? It's much better if it's a property — this way you don't have to check it every time:
public class Example : MonoBehaviour {
public Rigidbody projectile;
private bool _condition;
public bool Condition {
get { return _condition; }
set
{
if (_condition == value) return;
_condition = value;
if (value)
InvokeRepeating("LaunchProjectile", 2, 0.3F);
else
CancelInvoke("LaunchProjectile");
}
void LaunchProjectile() {
Rigidbody instance = Instantiate(projectile);
instance.velocity = Random.insideUnitSphere * 5;
}
}
Problem
I need to execute a code every x seconds till a condition is met in Unity3D C#. The code should run irrespective of other code as long as the condition is true and stop otherwise. As soon as the condition turns false, it should stop executing and run again if condition becomes true (counting no. of seconds from 0 again if possible). How to do that?