- Home /
Which of the Two is Better??
which of the two ways is the better in terms of Memory consumption,computation,usage etc and why??
private void Update()
{
//Statements
}
or
private void Start()
{
StartCoroutine (alternateToUpdate ());
}
private IEnumerator alternateToUpdate()
{
while (true)
{
//Statements
yield return 0;
}
}
You can check it yourself using the Unity profiler. Can't see any significant difference? Well there is your answer.
Answer by pako · Dec 16, 2017 at 09:10 AM
The`IEnumerator` would require some overhead while it's beeing created and also use slightly more memory, but I would consider these insignificant.
So, usage is the most important factor here.
As you may very well know, all code inside Update()
executes just once per frame. However, the code inside your IEnumerator
may execute indefinitely, even within the same frame, and may very well even freeze Unity, since while (true)
will keep calling the same code over and over again. So, if this code executes unconditionally, Unity will just freeze.
Use coroutines, when you need to wait for something to happen, whether it's a sound that needs to play fully, or timing an event, etc.
Also, consider InvokeRepeating()
https://docs.unity3d.com/ScriptReference/MonoBehaviour.InvokeRepeating.html
Also note that
yield return 0;
should never be used. Ins$$anonymous$$d use
yield return null;
When you yield a value type (and integer value in this case) you create garbage every time since a value type need to be boxed on the heap. If you yield "null" ins$$anonymous$$d of "0" there really isn't much of a difference.
Thanks a lot for the great explanation!! i completely understood difference between both and i would choose update over coroutines now!!
Answer by JedBeryll · Dec 16, 2017 at 09:01 AM
Not much difference here, depends on what kind of work you want to do. I would choose the one which is easier to work with.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
[Solved] How to disable function in same script? C# 2 Answers
Game Center login issue 0 Answers
Help me finish my room generator 0 Answers