码迷,mamicode.com
首页 > 编程语言 > 详细

Unity 中 使用c#线程

时间:2014-10-16 22:34:53      阅读:338      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   使用   ar   for   

       天下没有免费的午餐,在我使用unity的那一刻,我就感觉到不自在,因为开源所以不知道底层实现,如果只是简单的做点简单游戏,那就无所谓的了,但真正用到实际地方的时候,就会发现一个挨着一个坑,然后你就跟着unity做各种妥协。

注意点

       如果开发中需要使用网络等等涉及到多线程的地方,就会用到c#的多线程,注意不是unity的协程,你要做的妥协参考下面(网友整理,我没去搜索)的:

1. 变量(都能指向相同的内存地址)都是共享的

2. 不是UnityEngine的API能在分线程运行

3. UnityEngine定义的基本结构(int,float,Struct定义的数据类型)可以在分线程计算,如 Vector3(Struct)可以 , 但Texture2d(class,根父类为Object)不可以。

4  UnityEngine定义的基本类型的函数可以在分线程运行,类的函数不能在分线程运行

unity设计之初应该就是一个单线程,不允许在另外的线程中进行渲染等等的工作可以理解,不然又要增加很多机制去处理这个问题,会给新来的人徒增很多烦恼,比如说我:

//class
public class NIDataManager: MonoBehaviour
{
    private static NIDataManager instance = null;
    public static NIDataManager GetInstance()
    {
        if (!ServiceInterface.isInitSuccess)
        {
            Debug.Log("Application will exit because of Service open false");
            Application.Quit();
        }

        if (instance == null)
        {
            instance = GameObject.FindObjectOfType(typeof(NIDataManager)) as NIDataManager;
            if (instance == null)
            {
                Debug.Log("There needs to be one active NIServiceManager script on a GameObject in your scene.");
                Application.Quit();
            }
        }
        return instance;
    }
}
    /*thread*/
    private void RequestEvevtThread()
    {
        while (!m_IsExitThread)
        {
            /*wait set event*/
            m_EventWait.WaitOne(-1);

            /*reference SendRequestToService*/
            if (NIDataManager.GetInstance().isServiceOpen())
            //if (ServiceInterface.isInitSuccess)
            {
                if (0 == ServiceInterface.sendRequest((int)(m_EventParam.ActionType), m_EventParam.DurationTime, ref m_EventParam.Response))
                {
                    if (m_EventParam.DelegateCallback != null)
                    {
                        m_EventParam.DelegateCallback(m_EventParam.Response);
                    }
                }
                else
                {
                    // Debug.Log("sendRequest false");
                    continue;
                }
            }

            m_isProcessing = false;
        }
    }

 

如果你也这样干,恭喜你,会得到错误:CompareBaseObjectsInternal can only be called from the main thread.

关于这个错误的一些分析可以参考:http://forum.unity3d.com/threads/comparebaseobjectsinternal-error.184069/

Unity 中 使用c#线程

标签:style   blog   http   color   io   os   使用   ar   for   

原文地址:http://www.cnblogs.com/zsb517/p/4029521.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!