Use Unity API from another Thread or call a function in the main Thread

前端 未结 4 1446
醉梦人生
醉梦人生 2020-11-21 22:19

My problem is I try to use Unity socket to implement something. Each time, when I get a new message I need to update it to the updattext (it is a Unity Text). However, When

4条回答
  •  别跟我提以往
    2020-11-21 22:59

    I have been using this solution to this problem. Create a script with this code and attach it to a Game Object:

    using System;
    using System.Collections.Generic;
    using System.Collections.Concurrent;
    using UnityEngine;
    
    public class ExecuteOnMainThread : MonoBehaviour {
    
        public readonly ConcurrentQueue RunOnMainThread = new ConcurrentQueue();
    
        void Update()
        {
            if(!RunOnMainThread.IsEmpty)
            {
               Action action;
               while(RunOnMainThread.TryDequeue(out action))
               {
                 action.Invoke();
               }
            }
        }
    
    }
    

    Then when you need to call something on the main thread and access the Unity API from any other function in your application:

    ExecuteOnMainThread.RunOnMainThread.Enqueue(() => {
    
        // Code here will be called in the main thread...
    
    });
    

提交回复
热议问题