Unity 跨線程交互


Internal_CreateGameObject can only be called from the main thread

Unity的UI線程不允許其他線程訪問,但是logger線程是獨立的,所以如果你成功的輸出了日志,並不代表你就能快樂的訪問ui了

但是有的時候會出現不報錯,但是毫無反饋的情況,基本上也是同樣的問題造成的。

You can't access the Unity API from any thread outside of the main execution thread of Unity.

If you need data from Unity for a thread, you'll need to gather said information as a token and pass it along to the thread.

 

        /// <summary>
        /// 代理緩存
        /// </summary>
        class EventPacker
        {
            public MessageListener handler;
            public IMessage content;
        }
        public void Dispatch(eMessage id, IMessage message)
        {
            MessageListener handlers = null;

            if (SafeMessageListener.TryGetValue(id, out handlers))
            {
                if (handlers != null)
                {
                    EventQueue.Enqueue(new EventPacker { handler = handlers, content = message });
                }
            }
        }

        /// <summary>
        /// 只能由主線程來調用
        /// </summary>
        public void Update()
        {
            if (EventQueue.Count > 0)
            {
                var pack = EventQueue.Dequeue();
                pack.handler.Invoke(pack.content);
            }
        }

 

其實解決也很簡單,在任何一個MonoBehavior的update中調用上面的方法就可以了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM