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