Unity跨线程访问类实现

Unity跨线程访问类实现

unity中子线程无法使用unity中的方法,但很多时候我们需要在子线程中调用unity的方法(比如网络游戏),为了解决这个问题,我们就必须将需要在子线程调用的unity方法的代码,在主线程中执行。可是,如何能实现呢?既然是方法的传递,很容易想到 委托,为了在子线程能轻松将执行unity方法的代码放在主线程执行,可以将具体实现放在一个单例类中,即跨线程访问类。

具体代码实现:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//跨线程访问类,继承自单例类
public class AccrossThreadHelper : MonoSingleton<AccrossThreadHelper>
{
    //定义个无参数无返回值的委托类型(可根据需求改进)
    public delegate void AccrossThreadFunc();
    //一个委托集合
    private List<AccrossThreadFunc> delegateList;
    private void Start()
    {
        //初始化委托集合,并开启协程(Update替代协程也可以)
        delegateList = new List<AccrossThreadFunc>();
        StartCoroutine(Done());
    }

    //协程具体实现
    IEnumerator Done()
    {
        while(true)
        {
            if (delegateList.Count > 0)
            {
                //遍历委托链,依次执行
                foreach (AccrossThreadFunc item in delegateList)
                {
                    item();
                }
                //执行过的委托代码,清空
                delegateList.Clear();
            }
            yield return new WaitForSeconds(0.1f);
        }
    }
    //公开的添加委托方法
    public void AddDelegate(AccrossThreadFunc func)
    {
        delegateList.Add(func);
    }
}

调用格式:

AccrossThreadHelper.Instance.AddDelegate(() => { ...});

最后注意:

跨线程访问类的初始化,要在主线程进行(⊙o⊙)。

猜你喜欢

转载自blog.csdn.net/heroneverdie/article/details/80117846