子线程访问unity对象

14 篇文章 0 订阅

使用子线程是不能直接访问unity对象的,可以通过委托来访问。

using System;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;

public class Dispatcher : MonoBehaviour
{
    private static Dispatcher _instance;

    // We can't use the behaviour reference from other threads, so we use a separate bool
    // to track the instance so we can use that on the other threads.
    private static bool _instanceExists;

    private static Thread _mainThread;
    private static object _lockObject = new object();
    private static readonly Queue<Action> _actions = new Queue<Action>();

    /// <summary>
    /// Gets a value indicating whether or not the current thread is the game's main thread.
    /// </summary>
    public static bool isMainThread
    {
        get
        {
            return Thread.CurrentThread == _mainThread;
        }
    }

    /// <summary>
    /// Queues an action to be invoked on the main game thread.
    /// </summary>
    /// <param name="action">The action to be queued.</param>
    public static void InvokeAsync(Action action)
    {
        if (!_instanceExists)
        {
            Debug.LogError("No Dispatcher exists in the scene. Actions will not be invoked!");
            return;
        }

        if (isMainThread)
        {
            // Don't bother queuing work on the main thread; just execute it.
            action();
        }
        else
        {
            lock (_lockObject)
            {
                _actions.Enqueue(action);
            }
        }
    }

    /// <summary>
    /// Queues an action to be invoked on the main game thread and blocks the
    /// current thread until the action has been executed.
    /// </summary>
    /// <param name="action">The action to be queued.</param>
    public static void Invoke(Action action)
    {
        if (!_instanceExists)
        {
            Debug.LogError("No Dispatcher exists in the scene. Actions will not be invoked!");
            return;
        }

        bool hasRun = false;

        InvokeAsync(() =>
        {
            action();
            hasRun = true;
        });

        // Lock until the action has run
        while (!hasRun)
        {
            Thread.Sleep(5);
        }
    }

    void Awake()
    {
        if (_instance)
        {
            DestroyImmediate(this);
        }
        else
        {
            _instance = this;
            _instanceExists = true;
            _mainThread = Thread.CurrentThread;
        }
    }

    void OnDestroy()
    {
        if (_instance == this)
        {
            _instance = null;
            _instanceExists = false;
        }
    }

    void Update()
    {
        lock (_lockObject)
        {
            while (_actions.Count > 0)
            {
                _actions.Dequeue()();
            }
        }
    }
}

示例代码如下:

using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;

public class TestThread : MonoBehaviour
{
    public Text txt;
    private bool loop = true;
    // Use this for initialization
    void Start()
    {
        new Thread(() =>
        {
            while(loop)
            {
                UpdateText();
                //Dispatcher.Invoke(() => UpdateText());
                Thread.Sleep(1000);
            }
        }).Start();

    }
    private void OnDestroy()
    {
        loop = false;
    }
    private int index = 0;
    private void UpdateText()
    {
        this.txt.text = (index++).ToString();
    }
}

参考文章:https://www.cnblogs.com/lancidie/p/5877696.html

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值