- 多线程
- 协同
- 定义和使用
- 异步加载
- Resources.LoadAsync
- Resources.LoadAsync
多线程
引用命名空间:System.Threading;
Thread t = new Thread( 委托类型的参数 );
参数 ThreadStart(不带参的委托) ParameterizedThreadStart(带一个object参数的委托)
void Fun01() { }void Fun02( object o ) { }void Fun03( string name, int age ) { }void main(){Thread t1 = new Thread ( Fun01 );Thread t2 = new Thread ( new ThreadStart( Fun01 ) );Thread t3 = new Thread ( Fun02 );Thread t4 = new Thread ( new ParameterizedThreadStart ( Fun02 ) );// 使用lambda表达式实现多參传递Thread t5 = new Thread( ()=>{Fun03("name", 20);} );}
协同
Unity引擎不支持C#多线程
协同模拟了多线程的效果,借助每一个 Update 函数执行的空隙时间执行的函数体
协同函数是分段执行的函数,不是每次调用都执行完整
定义和使用
定义协同函数格式:
[修辞]IEnumerator 协同函数名(行參列表)
最多只能有一个参数
举例:
IEnumerator Run(){语句1;yield return new WaitForSeconds(等待时间);// 如果返回以后,下次进入协同方法会从返回的语句之后继续执行,执行完上面的代码后休息指定的秒数,它不会影响引擎更新函数语句2;yield return null; // 下一帧继续从后面的语句继续执行,存粹为了将函数分段if(条件)yield break; // 结束协同方法,后面的语句不再执行语句3;yield return new WaiForEndOfFrame(); // 表示在图形被渲染到帧缓存之后,在帧缓存渲染到屏幕上之前}
调用协同函数方法:
启动协同:
StartCoroutine(协同函数带实参列表);
举例:
// 此种方式最多只可以有1个参数// 只能调用当前对象的协同方法StartCoroutine("Run");// 停止协同StopCoroutine("Run");// 此种方式可以调用多參的方法// 可以调用其他对象的协同方法Coroutin co = StartCoroutine(Run());// 停止协同StopCoroutine(co);StopAllCoroutine();
终止协同:
StopCoroutine(正在运行的协同函数);
举例:
StopCoroutine("Run");StopAllCoroutine();
异步加载
Resources.LoadAsync
using UnityEngine;using System.Collections;public class ExampleClass : MonoBehaviour {void Start() {StartCoroutine(LoadTexture());}IEnumerator LoadTexture() {GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);ResourceRequest request = Resources.LoadAsync("glass");yield return request;go.renderer.material.mainTexture = request.asset as Texture2D;}}
using UnityEngine;using System.Collections;public class ExampleClass : MonoBehaviour {void Start() {StartCoroutine(LoadTexture());}IEnumerator LoadTexture() {GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);ResourceRequest request = Resources.LoadAsync<Texture2D>("glass");yield return request;go.renderer.material.mainTexture = request.asset;}}
