unity3D之协程的用法

MonoBehaviour.StartCoroutine

public Coroutine StartCoroutine(IEnumerator routine);

Description

Starts a coroutine.

The execution of a coroutine can be paused at any point using the yield statement. When a yield statement is used, the coroutine will pause execution and automatically resume at the next frame. See the Coroutines documentation for more details. Coroutines are excellent when modeling behavior over several frames. Coroutines have virtually no performance overhead. StartCoroutine function always returns immediately, however you can yield the result. Yielding waits until the coroutine has finished execution. There is no guarantee that coroutines end in the same order that they were started, even if they finish in the same frame.

An example of StartCoroutine:

using UnityEngine;
using System.Collections;// In this example we show how to invoke a coroutine and
// continue executing the function in parallel.public class ExampleClass : MonoBehaviour
{
    // In this example we show how to invoke a coroutine and
    // continue executing the function in parallel.    private IEnumerator coroutine;    void Start()
    {
        // - After 0 seconds, prints "Starting 0.0"
        // - After 0 seconds, prints "Before WaitAndPrint Finishes 0.0"
        // - After 2 seconds, prints "WaitAndPrint 2.0"
        print("Starting " + Time.time);        // Start function WaitAndPrint as a coroutine.        coroutine = WaitAndPrint(2.0f);
        StartCoroutine(coroutine);        print("Before WaitAndPrint Finishes " + Time.time);
    }    // every 2 seconds perform the print()
    private IEnumerator WaitAndPrint(float waitTime)
    {
        while (true)
        {
            yield return new WaitForSeconds(waitTime);
            print("WaitAndPrint " + Time.time);
        }
    }
}

Another example:

// In this example we show how to invoke a coroutine and wait until it
// is completedusing UnityEngine;
using System.Collections;public class ExampleClass : MonoBehaviour
{
    IEnumerator Start()
    {
        // - After 0 seconds, prints "Starting 0.0"
        // - After 2 seconds, prints "WaitAndPrint 2.0"
        // - After 2 seconds, prints "Done 2.0"
        print("Starting " + Time.time);        // Start function WaitAndPrint as a coroutine. And wait until it is completed.
        // the same as yield WaitAndPrint(2.0);
        yield return StartCoroutine(WaitAndPrint(2.0F));
        print("Done " + Time.time);
    }    // suspend execution for waitTime seconds
    IEnumerator WaitAndPrint(float waitTime)
    {
        yield return new WaitForSeconds(waitTime);
        print("WaitAndPrint " + Time.time);
    }
}

public Coroutine StartCoroutine(string methodName, object value = null);

Description

Starts a coroutine named methodName.

In most cases you want to use the StartCoroutine variation above. However StartCoroutine using a string method name allows you to use StopCoroutine with a specific method name. The downside is that the string version has a higher runtime overhead to start the coroutine and you can pass only one parameter.

// In this example we show how to invoke a coroutine using a string name and stop it.using UnityEngine;
using System.Collections;public class ExampleClass : MonoBehaviour
{
    IEnumerator Start()
    {
        StartCoroutine("DoSomething", 2.0F);
        yield return new WaitForSeconds(1);
        StopCoroutine("DoSomething");
    }    IEnumerator DoSomething(float someParameter)
    {
        while (true)
        {
            print("DoSomething Loop");            // Yield execution of this coroutine and return to the main loop until next frame
            yield return null;
        }
    }
}

Parameters

coroutineName of the created Coroutine.

Description

Starts a Coroutine named coroutine.

Create a Coroutine. Any coroutine name can be used. A StartCoroutine function terminates immediately, however, the Coroutine it creates runs as expected. A created coroutine can start another coroutine. These two coroutines can operate together in many ways. This includes both coroutine running in parallel. Alternatively one coroutine can stop the other while it continues itself. The script example below shows one coroutine pausing as it starts another one. Once this second coroutine finishes it restarts the first one.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class ExampleClass : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(coroutineA());
    }    
    IEnumerator coroutineA()
    {
        // wait for 1 second
        Debug.Log("coroutineA created");
        yield return new WaitForSeconds(1.0f);
        yield return StartCoroutine(coroutineB());
        Debug.Log("coroutineA running again");
    }   
    IEnumerator coroutineB()
    {
        Debug.Log("coroutineB created");
        yield return new WaitForSeconds(2.5f);
        Debug.Log("coroutineB enables coroutineA to run");
    }
}

MonoBehaviour.StopAllCoroutines

public void StopAllCoroutines();

Description

Stops all coroutines running on this behaviour.

A MonoBehaviour can execute zero or more coroutines. Created coroutines can execute for a range of times. In the script example below two coroutines are created and run without stopping. However, StopAllCoroutines is used to stop both of them. This action can be made to happen on a script that runs multiple coroutines. No arguments are needed because all coroutines on a script are stopped.
Note: StopAllCoroutines operates only on the one script it is attached to.

using UnityEngine;
using System.Collections;// Create two coroutines that run at different speeds.
// When the space key is pressed stop both of them.public class ExampleClass : MonoBehaviour
{
    //coroutine 1
    IEnumerator DoSomething1()
    {
        while (true)
        {
            print("DoSomething1");
            yield return new WaitForSeconds(1.0f);
        }
    }    //coroutine 2
    IEnumerator DoSomething2()
    {
        while (true)
        {
            print("DoSomething2");
            yield return new WaitForSeconds(1.5f);
        }
    }    
    void Start()
    {
        StartCoroutine("DoSomething1");
        StartCoroutine("DoSomething2");
    }    
    void Update()
    {
        if (Input.GetKeyDown("space"))
        {
            StopAllCoroutines();
            print("Stopped all Coroutines: " + Time.time);
        }
    }
}

MonoBehaviour.StopCoroutine

public void StopCoroutine(string methodName);

public void StopCoroutine(IEnumerator routine);

public void StopCoroutine(Coroutine routine);

Parameters

methodNameName of coroutine.
routineName of the function in code, including coroutines.

Description

Stops the first coroutine named methodName, or the coroutine stored in routine running on this behaviour.

StopCoroutine takes one of three arguments which specify which coroutine is stopped:

- A string function naming the active coroutine
- The IEnumerator variable used earlier to create the coroutine.
- The Coroutine to stop the manually created Coroutine.

Note: Do not mix the three arguments. If a string is used as the argument in StartCoroutine, use the string in StopCoroutine. Similarly, use the IEnumerator in both StartCoroutine and StopCoroutine. Finally, use StopCoroutine with the Coroutine used for creation.

In the CS example, the IEnumerator type is used.

using UnityEngine;
using System.Collections;public class Example : MonoBehaviour
{
    // keep a copy of the executing script
    private IEnumerator coroutine;    // Use this for initialization
    void Start()
    {
        print("Starting " + Time.time);
        coroutine = WaitAndPrint(3.0f);
        StartCoroutine(coroutine);
        print("Done " + Time.time);
    }    // print to the console every 3 seconds.
    // yield is causing WaitAndPrint to pause every 3 seconds
    public IEnumerator WaitAndPrint(float waitTime)
    {
        while (true)
        {
            yield return new WaitForSeconds(waitTime);
            print("WaitAndPrint " + Time.time);
        }
    }    
    void Update()
    {
        if (Input.GetKeyDown("space"))
        {
            StopCoroutine(coroutine);
            print("Stopped " + Time.time);
        }
    }
}

The following cs example shows how StopCoroutine(Coroutine) can be used.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class ExampleClass : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(coroutineA());
    }    
    IEnumerator coroutineA()
    {
        // wait for 1 second
        yield return new WaitForSeconds(1.0f);
        Debug.Log("coroutineA() started: " + Time.time);        
        // wait for another 1 second and then create b
        yield return new WaitForSeconds(1.0f);
        Coroutine b = StartCoroutine(coroutineB());        
        yield return new WaitForSeconds(2.0f);
        Debug.Log("coroutineA() finished " + Time.time);       
        // B() was expected to run for 10 seconds
        // but was shut down here after 3.0f
        StopCoroutine(b);
        yield return null;
    }    
    IEnumerator coroutineB()
    {
        float f = 0.0f;
        float start = Time.time;        
        Debug.Log("coroutineB() started " + start);        
        while (f < 10.0f)
        {
            Debug.Log("coroutineB(): " + f);
            yield return new WaitForSeconds(1.0f);
            f = f + 1.0f;
        }        
        // Intended to handling exit of the this coroutine.
        // However coroutineA() shuts coroutineB() down. This
        // means the following lines are not called.
        float t = Time.time - start;
        Debug.Log("coroutineB() finished " + t);
        yield return null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值