首页 > 编程语言 > 详细

Unity 跨线程交互

时间:2020-03-30 18:46:07      阅读:92      评论:0      收藏:0      [点我收藏+]

Internal_CreateGameObject can only be called from the main thread

Unity的UI线程不允许其他线程访问,但是logger线程是独立的,所以如果你成功的输出了日志,并不代表你就能快乐的访问ui了

但是有的时候会出现不报错,但是毫无反馈的情况,基本上也是同样的问题造成的。

You cant access the Unity API from any thread outside of the main execution thread of Unity.

If you need data from Unity for a thread, youll 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中调用上面的方法就可以了。

Unity 跨线程交互

原文:https://www.cnblogs.com/Fivee/p/12600194.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!