- Home /
Using a while loop in coroutine as a contained Update function
Are there any drawbacks to using
private IEnumerator ContainedFunction()
{
while (true)
{
this.transform.position = box.transform.position;
yield return null;
}
}
Versus
void Update()
{
if (randomBool)
{
this.transform.position = box.transform.position;
}
}
If the code it was running was more complex, would I suffer any potential problems?
Disabling a game object kills coroutines. So one difference is that if you disable and then reenable the game object that this script is attached to, the coroutine will no longer be running. You could restart it in OnEnable().
Answer by Jessy · Jun 27, 2013 at 04:00 PM
Coroutine are never a good idea. They are not controllable the way Update is; i.e. they're a pain. If statements are clutter. So, neither of the methods you displayed is desirable.
Instead, always use a delegate in Update, and add to and remove from it as necessary. Then, you can just disable the script to disable all delegates. I derive from this:
public abstract class AutoDisablingMonoBehaviour : MonoBehaviour {
Action handleUpdate;
protected Action HandleUpdate {
get { return handleUpdate; }
set {
handleUpdate = value;
if (handleUpdate == null)
enabled = false;
else if (!enabled)
enabled = true;
}
}
protected virtual void Reset() {
enabled = false;
}
void Update() {
handleUpdate();
}
}
Your answer
Follow this Question
Related Questions
Play animation 5 sec, stop for 5 seconds, repeat 0 Answers
Why is this coroutine only firing once? 3 Answers
StopCoroutine() is not stopping my coroutines 1 Answer
Simplify this code 3 Answers