Fivee

导航

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中调用上面的方法就可以了。

posted on 2020-03-30 18:08  Fivee  阅读(1352)  评论(0)    收藏  举报