Startcoroutine is called coroutine in the help of unity3d, which means to start an auxiliary thread.
There is a thread in C #, but some elements in unity cannot be operated. The coroutine can be used in this case.
The advantage of using a thread is that there will be no interface failure. If there is a large number of operations, the thread will be suspended if it is useless.
Here is a simple example to illustrate the benefits of using coroutine:
[CSHARP]View plaincopy
- Void ongui ()
- {
- Gui. Label (New rect (0, 0,200, 50), "Test 1:" + result );
- If (GUI. Button (New rect (0,100,100, 50), "enable coroutine "))
- {
- Startcoroutine (getresult ());
- }
- Gui. Label (New rect (200, 0,200, 50), "Test 2:" + result1 );
- If (GUI. Button (New rect (200,100,100, 50), "No coroutine test "))
- {
- Getresult1 ();
- }
- }
The above Code defines two labels and buttons in the GUI. One button starts the coroutine calculation and the other directly calculates the result. Because the two methods both calculate the same result and the calculation amount is large, a temporary card death occurs during direct calculation.
[CSHARP]View plaincopy
- Float result;
- Ienumerator getresult ()
- {
- For (INT I = 0; I <1000; I ++)
- {
- For (Int J = 0; j <100000; j ++)
- {
- Result + = (I + J );
- }
- If (I % 100 = 0)
- Yield return 1;
- }
- }
This method is used to write coroutine. in C #, The coroutine must be defined as ienumerator, which is not required in JavaScript.
Yield return 1; this statement indicates that the result of one frame is returned. When I is an integer of 100, a result is returned once. This prevents a large number of computations from getting stuck.
[CSHARP]View plaincopy
- Float result1;
- Void getresult1 ()
- {
- For (INT I = 0; I <1000; I ++)
- {
- For (Int J = 0; j <100000; j ++)
- {
- Result1 + = (I + J );
- }
- }
- }
This method directly calculates the result. Because of the large amount of computing, the interface will be stuck, which will reflect the benefits of using coroutine.
When you use ienumerator, you must use yield return to return results. If the parameter is a number, it indicates the number of frames.
For example, yield return 1 indicates that each frame returns a result.
Use of startcoroutine