Exemplo n.º 1
0
    public override void Init()
    {
        base.Init();

        //提示
//        var isCodeHotfix = GameObject.Find("BDFrame").GetComponent<BDLauncher>().IsCodeHotfix;
//        text_hotfixState.text = isCodeHotfix ? "热更模式:开" : "热更模式:关";

        //demo1: screenview 切换
        this.btn_01.onClick.AddListener(() => { ScreenViewManager.Inst.MainLayer.BeginNavTo("demo1"); });

        //demo2: ui window基本操作
        this.btn_02.onClick.AddListener(() =>
        {
            ScreenViewManager.Inst.MainLayer.BeginNavTo("demo2");

            //向demo2窗口发消息
            var d = WindowData.Create("rotation");
            d.AddData("rotation", UnityEngine.Random.Range(-359, 359));
            UIManager.Inst.SendMessage((int)WinEnum.Win_Demo2, d);
        });

        //demo3: uimvc模式
        this.btn_03.onClick.AddListener(() => { ScreenViewManager.Inst.MainLayer.BeginNavTo("demo3"); });

        //demo4: uitools使用
        this.btn_04.onClick.AddListener(() =>
        {
            UIManager.Inst.LoadWindows((int)WinEnum.Win_Demo4);
            UIManager.Inst.ShowWindow((int)WinEnum.Win_Demo4);
        });
        //demo5: sqlite 查询
        this.btn_05.onClick.AddListener(() =>
        {
            var ds = SqliteHelper.DB.GetTableRuntime().Where("id > 1").ToSearch <Hero>();

            foreach (var d in ds)
            {
                Debug.Log(JsonMapper.ToJson(d));
            }
        });
        //demo6:资源加载
        this.btn_06.onClick.AddListener(() =>
        {
            //1.同步加载
            var go = BResources.Load <GameObject>("Windows/window_demo1");

            //2.异步加载单个
            var id = BResources.AsyncLoad <GameObject>("Windows/window_demo1", (b, o) => { });
//            //取消任务
//            BResources.LoadCancel(id);6
//
//          //3.异步加载多个
            BResources.AsyncLoad(new List <string>()
            {
                "Windows/window_demo1", "Windows/window_demo2"
            },
                                 (i, i2) => { Debug.Log(string.Format("进度 {0} / {1}", i, i2)); }, (map) =>
            {
                BDebug.Log("加载全部完成,资源列表:");
                foreach (var r in map)
                {
                    BDebug.Log(string.Format("--> {0} : {1}", r.Key, r.Value.name));
                    GameObject.Instantiate(r.Value);
                }
            });
        });

        this.btn_07.onClick.AddListener(() =>
        {
            var path = Application.streamingAssetsPath;

            VersionContorller.Start("http://127.0.0.1", path,
                                    (i, j) =>
            {
                Debug.LogFormat("资源更新进度:{0}/{1}", i, j);
            },
                                    (error) =>
            {
                Debug.LogError("错误:" + error);
            });
        });
    }
Exemplo n.º 2
0
        /// <summary>
        /// 母包资源检测逻辑
        /// </summary>
        /// <returns></returns>
        static public void CheckBasePackageVersion(RuntimePlatform platform, Action callback)
        {
            //路径初始化
            var persistentPlatformPath = IPath.Combine(Application.persistentDataPath, BApplication.GetPlatformPath(platform));
            //母包路径
            string basePckPath = "";

            //母包路径不同情况不一样
            switch (BDLauncher.Inst.GameConfig.ArtRoot)
            {
            case AssetLoadPathType.Editor:
            {
                //editor不进行母包资源管理
                BDebug.Log("【资源包】Editor加载不执行:母包资源检测逻辑!");
                callback?.Invoke();
                return;
            }

            case AssetLoadPathType.Persistent:
            case AssetLoadPathType.StreamingAsset:
            {
                isUseSysIO  = false;
                basePckPath = BApplication.streamingAssetsPath;
            }
            break;

            case AssetLoadPathType.DevOpsPublish:
            {
                isUseSysIO  = true;
                basePckPath = BApplication.DevOpsPath;
            }
            break;
            }
            BDebug.Log("【资源包】执行母包资源检测逻辑!");
            //源地址
            string basePckPlatformPath = "";

            if (isUseSysIO)
            {
                basePckPlatformPath = IPath.Combine(basePckPath, BApplication.GetPlatformPath(platform));
            }

            //packageinfo
            var persistentPackageBuildInfoPath = IPath.Combine(persistentPlatformPath, BResources.PACKAGE_BUILD_INFO_PATH);
            var basePckBuildInfoPath           = IPath.Combine(basePckPlatformPath, BResources.PACKAGE_BUILD_INFO_PATH);

            if (!IsExsitAsset(basePckBuildInfoPath))
            {
                //不存在Streaming配置
                BDebug.LogError("【母包资源检测】拷贝失败,不存在:" + basePckBuildInfoPath);
                callback?.Invoke();
                return;
            }
            else
            {
                var basePckBuildInfoContent = ReadAssetAllText(basePckBuildInfoPath);
                //persitent存在,判断版本
                if (!IsExsitAsset(persistentPackageBuildInfoPath))
                {
                    var content = ReadAssetAllText(persistentPackageBuildInfoPath);
                    //解析
                    var persistentPackageInfo = JsonMapper.ToObject <BasePackageAssetsBuildInfo>(content);
                    var basePackageInfo       = JsonMapper.ToObject <BasePackageAssetsBuildInfo>(basePckBuildInfoContent);
                    if (persistentPackageInfo.BuildTime >= basePackageInfo.BuildTime)
                    {
                        //跳出,检测结束
                        BDebug.Log("【母包资源检测】不复制,母包 无新资源");
                        callback?.Invoke();
                        return;
                    }
                    else
                    {
                        BDebug.Log("【母包资源检测】复制,母包 有新资源,即将清理persistent旧资源!!!!", "yellow");
                        ClearOldPersistentAssets();
                        //Streaming版本比较新
                        //复制Stream的packageinfo 到persistent
                        FileHelper.WriteAllText(persistentPackageBuildInfoPath, basePckBuildInfoContent);
                    }
                }
                else
                {
                    BDebug.Log("【母包资源检测】第一次创建资源包info到persistent目录");
                    //persistent版本不存在
                    //复制Stream的packageinfo 到persistent
                    FileHelper.WriteAllText(persistentPackageBuildInfoPath, basePckBuildInfoContent);
                }
            }

            //开始拷贝逻辑
            for (int i = 0; i < PersistentOnlyFiles.Length; i++)
            {
                var copytoFile = PersistentOnlyFiles[i];
                //复制新版本的DLL
                var persistentPath   = IPath.Combine(persistentPlatformPath, copytoFile);
                var basePckAssetPath = IPath.Combine(basePckPlatformPath, copytoFile);

                //开始拷贝
                if (IsExsitAsset(basePckAssetPath))
                {
                    BDebug.Log("【母包资源检测】复制成功:" + copytoFile);
                    var bytes = ReadFileAllBytes(basePckAssetPath, isUseSysIO);
                    FileHelper.WriteAllBytes(persistentPath, bytes);
                }
                else
                {
                    BDebug.LogError("【母包资源检测】复制失败,本地不存在:" + copytoFile);
                }
            }

            //结束
            callback?.Invoke();
        }
Exemplo n.º 3
0
    /// <summary>
    /// 主循环
    /// </summary>
    void Update()
    {
        //停止所有携程
        if (isStopAllCroutine)
        {
            BDebug.Log("停止所有携程");
            StopAllCoroutines();
            isStopAllCroutine = false;
        }
        //优先停止携程
        while (stopIEIdQueue.Count > 0)
        {
            var id = stopIEIdQueue.Dequeue();
            if (coroutineDictionary.ContainsKey(id))
            {
                var coroutine = coroutineDictionary[id];
                base.StopCoroutine(coroutine);
                //
                coroutineDictionary.Remove(id);
            }
            else
            {
                Debug.LogErrorFormat("此id协程不存在,无法停止:{0}", id);
            }
        }

        //携程循环
        if (IEnumeratorQueue.Count > 0)
        {
            var id = IEnumeratorQueue.Dequeue();
            //取出携程
            var ie = iEnumeratorDictionary[id];
            iEnumeratorDictionary.Remove(id);
            //执行携程
            var coroutine = base.StartCoroutine(ie);

            //存入coroutine
            coroutineDictionary[id] = coroutine;
        }

        //主线程循环 立即执行
        while (actionTaskQueueImmediately.Count > 0)
        {
            var task = actionTaskQueueImmediately.Dequeue();
            task.willDoAction();
            if (task.callBackAction != null)
            {
                task.callBackAction();
            }
        }

        //主线程循环
        if (m_actionTaskQueue.Count > 0)
        {
            var task = m_actionTaskQueue.Dequeue();
            task.willDoAction();
            if (task.callBackAction != null)
            {
                task.callBackAction();
            }
        }
    }
Exemplo n.º 4
0
 public void Do()
 {
     BDebug.Log("-------------这是demo2的 log---------", "yellow");
 }
Exemplo n.º 5
0
    private void NetWorkStateChange(NetWorkState state)
    {
        netWorkState = state;
        BDebug.Log(state);
        switch (state)
        {
        case NetWorkState.CLOSED:
        {
            BDebug.Log("关闭:" + host);
        }
        break;

        case NetWorkState.CONNECTING:
        {
            BDebug.Log("连接:" + host + " --连接中");
        }
        break;

        case NetWorkState.CONNECTED:
        {
            BDebug.Log("连接:" + host + " --连接上");
        }
        break;

        case NetWorkState.WORK:
        {
            IEnumeratorTool.ExecAction(() =>
                {
                    //UIWidgetMgr.Inst.Turn_Chrysanthemum.Hide();
                });
            BDebug.Log("连接:" + host + " --正常工作");
        }
        break;

        case NetWorkState.DISCONNECTED:
        {
            if (isByClientCall)
            {
                isByClientCall = false;
            }
            else
            {
                if (OnDisconnect != null)
                {
                    IEnumeratorTool.ExecAction(() =>
                        {
                            OnDisconnect();
                        });
                }
            }
        }
        break;

        case NetWorkState.TIMEOUT:
        case NetWorkState.ERROR:
        {
            if (OnTimeOut != null)
            {
                IEnumeratorTool.ExecAction(() =>
                    {
                        OnTimeOut();
                    });
            }
        }
        break;

        default:
            break;
        }
    }
Exemplo n.º 6
0
    private static void AnalyzeResource(string[] paths, BuildTarget target, string outpath)
    {
        var configPath = IPath.Combine(outpath, "Art/Config.json");

        if (File.Exists(configPath))
        {
            var content = File.ReadAllText(configPath);
            manifestConfig = new ManifestConfig(content);
        }
        else
        {
            manifestConfig = new ManifestConfig();
        }

        int   counter  = 0;
        float curIndex = 0;

        foreach (var path in paths)
        {
            var _path = path.Replace("\\", "/");

            EditorUtility.DisplayProgressBar("分析资源 -" + target.ToString(),
                                             "分析:" + Path.GetFileNameWithoutExtension(_path) + "   进度:" + curIndex + "/" + paths.Length,
                                             curIndex / paths.Length);
            curIndex++;
            //获取被依赖的路径
            var dependsource         = "Assets" + _path.Replace(Application.dataPath, "");
            var allDependObjectPaths = AssetDatabase.GetDependencies(dependsource).ToList();

            var manifestItem = manifestConfig.GetManifestItem(dependsource.ToLower());
            var Uiid         = GetMD5HashFromFile(_path);
            //
            var           isEquals  = manifestItem != null && Uiid == manifestItem.UIID;
            List <string> newAssets = new List <string>();
            //处理依赖资源是否打包
            for (int i = 0; i < allDependObjectPaths.Count; i++)
            {
                //
                var dependPath = allDependObjectPaths[i];
                var ext        = Path.GetExtension(dependPath).ToLower();
                if (ext == ".cs" || ext == ".js")
                {
                    continue;
                }

                //
                AssetImporter ai = AssetImporter.GetAtPath(dependPath);
                if (ai == null)
                {
                    BDebug.Log("not find Resource " + dependPath);
                    continue;
                }


                //重新组建ab名字,带上路径名
                dependPath = Path.GetFullPath(dependPath);
                dependPath = dependPath.Replace("\\", "/");
                //根据是否相等,判断是否打包
                if (isEquals)
                {
                    //本次不打包
                    ai.assetBundleName = null;
                }
                else
                {
                    //本次打包
                    string derictory = "assets" + dependPath.Replace(Application.dataPath, "");
                    ai.assetBundleName = derictory.ToLower();

                    newAssets.Add(ai.assetBundleName);
                    ai.assetBundleVariant = "";
                }
            }


            //将现在的目录结构替换配置中的
            if (newAssets.Count > 0)
            {
                manifestConfig.AddDepend(dependsource.ToLower(), Uiid, newAssets);
                counter++;
            }
        }

        Debug.Log("本地需要打包资源:" + counter);
    }
Exemplo n.º 7
0
        public static void LoadHotfix(string dllPath, bool isRegisterBindings = true)
        {
            //
            IsRunning = true;
            string pdbPath = dllPath.Replace(".dll", ".pdb");

            BDebug.Log("DLL加载路径:" + dllPath, "red");
            //
            AppDomain = new AppDomain();
            if (File.Exists(pdbPath))
            {
                //这里的流不能释放,头铁的老哥别试了
                fsDll = new FileStream(dllPath, FileMode.Open, FileAccess.Read);
                fsPdb = new FileStream(pdbPath, FileMode.Open, FileAccess.Read);
                AppDomain.LoadAssembly(fsDll, fsPdb, new PdbReaderProvider());
            }
            else
            {
                //这里的流不能释放,头铁的老哥别试了
                fsDll = new FileStream(dllPath, FileMode.Open, FileAccess.Read);
                AppDomain.LoadAssembly(fsDll);
            }


#if UNITY_EDITOR
            AppDomain.UnityMainThreadID = System.Threading.Thread.CurrentThread.ManagedThreadId;
#endif

            //绑定的初始化
            //ada绑定
            AdapterRegister.RegisterCrossBindingAdaptor(AppDomain);
            //delegate绑定
            ILRuntimeDelegateHelper.Register(AppDomain);
            //值类型绑定
            AppDomain.RegisterValueTypeBinder(typeof(Vector2), new Vector2Binder());
            AppDomain.RegisterValueTypeBinder(typeof(Vector3), new Vector3Binder());
            AppDomain.RegisterValueTypeBinder(typeof(Vector4), new Vector4Binder());
            AppDomain.RegisterValueTypeBinder(typeof(Quaternion), new QuaternionBinder());



            //是否注册各种binding
            if (isRegisterBindings)
            {
                ILRuntime.Runtime.Generated.CLRBindings.Initialize(AppDomain);
                ILRuntime.Runtime.Generated.CLRManualBindings.Initialize(AppDomain);
                // ILRuntime.Runtime.Generated.PreCLRBuilding.Initialize(AppDomain);
            }

            JsonMapper.RegisterILRuntimeCLRRedirection(AppDomain);


            if (Application.isEditor)
            {
                AppDomain.DebugService.StartDebugService(56000);
                Debug.Log("热更调试器 准备待命~");
            }

            //
            AppDomain.Invoke("HotfixCheck", "Log", null, null);
        }
Exemplo n.º 8
0
    public SQLiteService(string dbName)
    {
        //#if UNITY_EDITOR
        //        var dbPath = string.Format(@"Assets/StreamingAssets/{0}", DatabaseName);
        //#else
        //        var filepath = string.Format("{0}/{1}", Application.persistentDataPath, DatabaseName);

        //        if (!File.Exists(filepath))
        //        {
        //            Debug.Log("Database not in Persistent path");
        //            // if it doesn't ->
        //            // open StreamingAssets directory and load the db ->

        //#if UNITY_ANDROID
        //            var loadDb =
        //new WWW("jar:file://" + Application.dataPath + "!/assets/" + DatabaseName);  // this is the path to your StreamingAssets in android
        //            while (!loadDb.isDone) { }  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
        //            // then save to Application.persistentDataPath
        //            File.WriteAllBytes(filepath, loadDb.bytes);
        //#elif UNITY_IOS
        //                 var loadDb =
        //Application.dataPath + "/Raw/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
        //                // then save to Application.persistentDataPath
        //                File.Copy(loadDb, filepath);
        //#elif UNITY_WP8
        //                var loadDb =
        //Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
        //                // then save to Application.persistentDataPath
        //                File.Copy(loadDb, filepath);

        //#elif UNITY_WINRT
        //		var loadDb =
        //Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
        //		// then save to Application.persistentDataPath
        //		File.Copy(loadDb, filepath);

        //#elif UNITY_STANDALONE_OSX
        //		var loadDb =
        //Application.dataPath + "/Resources/Data/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
        //		// then save to Application.persistentDataPath
        //		File.Copy(loadDb, filepath);
        //#else
        //	var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;
        //            // this is the path to your StreamingAssets in iOS
        //	// then save to Application.persistentDataPath
        //	File.Copy(loadDb, filepath);

        //#endif

        //          // Debug.Log("Database written");
        //        }

        //var dbPath = filepath;
        //#endif


        if (Application.isEditor)
        {
            dbName = Path.Combine(Application.streamingAssetsPath, dbName);
        }
        else
        {
            //非editor下在persistent目录下
            dbName = Path.Combine(Application.persistentDataPath, dbName);
        }


        BDebug.Log("open db:" + dbName);
        DB = new SQLiteConnection(dbName, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create);
    }
Exemplo n.º 9
0
 public void Start()
 {
     // Application.targetFrameRate = 24;
     BDebug.Log("启动器1 启动成功!", "red");
     IsAwake = true;
 }
Exemplo n.º 10
0
        protected void Dispose(bool disposing)
        {
            BDebug.Log(debugType, "BDynamicsWorld Disposing physics.");

            if (m_world != null)
            {
                //remove/dispose constraints
                int i;
                if (_ddWorld != null)
                {
                    for (i = _ddWorld.NumConstraints - 1; i >= 0; i--)
                    {
                        TypedConstraint constraint = _ddWorld.GetConstraint(i);
                        _ddWorld.RemoveConstraint(constraint);
                        if (constraint.Userobject is BTypedConstraint)
                        {
                            ((BTypedConstraint)constraint.Userobject).isInWorld = false;
                        }
                        if ((debugType & BDebug.DebugType.Debug) == BDebug.DebugType.Debug)
                        {
                            Debug.LogFormat("Removed Constaint {0}", constraint.Userobject);
                        }
                        constraint.Dispose();
                    }
                }

                //remove the rigidbodies from the dynamics world and delete them
                for (i = m_world.NumCollisionObjects - 1; i >= 0; i--)
                {
                    CollisionObject obj  = m_world.CollisionObjectArray[i];
                    RigidBody       body = obj as RigidBody;
                    if (body != null && body.MotionState != null)
                    {
                        body.MotionState.Dispose();
                    }
                    m_world.RemoveCollisionObject(obj);
                    if (obj.UserObject is BCollisionObject)
                    {
                        ((BCollisionObject)obj.UserObject).isInWorld = false;
                    }
                    if ((debugType & BDebug.DebugType.Debug) == BDebug.DebugType.Debug)
                    {
                        Debug.LogFormat("Removed CollisionObject {0}", obj.UserObject);
                    }
                    obj.Dispose();
                }

                if (m_world.DebugDrawer != null)
                {
                    if (m_world.DebugDrawer is IDisposable)
                    {
                        IDisposable dis = (IDisposable)m_world.DebugDrawer;
                        dis.Dispose();
                    }
                }

                m_world.Dispose();
                Broadphase.Dispose();
                Dispatcher.Dispose();
                CollisionConf.Dispose();
                _ddWorld = null;
                m_world  = null;
            }

            if (Broadphase != null)
            {
                Broadphase.Dispose();
                Broadphase = null;
            }
            if (Dispatcher != null)
            {
                Dispatcher.Dispose();
                Dispatcher = null;
            }
            if (CollisionConf != null)
            {
                CollisionConf.Dispose();
                CollisionConf = null;
            }
            if (Solver != null)
            {
                Solver.Dispose();
                Solver = null;
            }
            if (softBodyWorldInfo != null)
            {
                softBodyWorldInfo.Dispose();
                softBodyWorldInfo = null;
            }
            _isDisposed = true;
            singleton   = null;
        }
Exemplo n.º 11
0
        /// <summary>
        /// 加载接口
        /// </summary>
        /// <param name="configPath"></param>
        /// <param name="onLoaded"></param>
        public void Load(string configPath, string assetTypePath)
        {
            //资源类型配置
            if (!string.IsNullOrEmpty(assetTypePath) && File.Exists(assetTypePath))
            {
                var content = File.ReadAllText(assetTypePath);
                // var list = CsvSerializer.DeserializeFromString<List<string>>(content);
                // var wlist = new List<AssetTypes>()
                // {
                //     new AssetTypes()
                //     {
                //         AssetTypeList = list,
                //     }
                // };
                // var str = CsvSerializer.SerializeToCsv(wlist);
                // File.WriteAllText(assetTypePath, str);
                // //
                // content = File.ReadAllText(assetTypePath);
                var records = CsvSerializer.DeserializeFromString <List <AssetTypeConfig> >(content);
                this.AssetTypes = records[0];
                //创建不同类型的映射表
                foreach (var assetType in this.AssetTypes.AssetTypeList)
                {
                    this.assetTypeIdxMap[assetType] = new LoadPathIdxMap();
                }
            }
            else
            {
                BDebug.LogError("配置文件不存在:" + configPath);
            }

            //资源配置
            if (!string.IsNullOrEmpty(configPath) && File.Exists(configPath))
            {
                this.configPath = configPath;
#if UNITY_EDITOR
                Stopwatch sw = new Stopwatch();
                sw.Start();
#endif
                var content = File.ReadAllText(configPath);
                this.AssetbundleItemList = CsvSerializer.DeserializeFromString <List <AssetBundleItem> >(content);
#if UNITY_EDITOR
                sw.Stop();
                BDebug.LogFormat("【AssetbundleV2】加载Config耗时{0}ms!", sw.ElapsedTicks / 10000L);
#endif


                foreach (var abItem in this.AssetbundleItemList)
                {
                    //可以被加载的资源
                    if (!string.IsNullOrEmpty(abItem.LoadPath) && this.AssetTypes != null)
                    {
                        var assettype = this.AssetTypes.AssetTypeList[abItem.AssetType];
                        var map       = this.assetTypeIdxMap[assettype];
                        map[abItem.LoadPath] = abItem.Id;
                    }
                }
            }
            else
            {
                BDebug.LogError("配置文件不存在:" + configPath);
            }

            //初始化常用资源类型
            // if (this.AssetTypes != null)
            // {
            //     //Prefab
            //     var clsName = typeof(GameObject).FullName;
            //     AssetType.VALID_TYPE_PREFAB = this.AssetTypes.AssetTypeList.FindIndex((at) => at.Equals(clsName, StringComparison.OrdinalIgnoreCase));
            //     //图集
            //     clsName = typeof(SpriteAtlas).FullName;
            //     AssetType.VALID_TYPE_SPRITE_ATLAS = this.AssetTypes.AssetTypeList.FindIndex((at) => at.Equals(clsName, StringComparison.OrdinalIgnoreCase));
            //     //...
            //     //其他省略,需要时候再加
            // }


            BDebug.Log("【AssetbundleV2】资源加载初始化完成,资源总量:" + this.AssetbundleItemList?.Count);
        }
Exemplo n.º 12
0
        /// <summary>
        /// 添加sql缓存
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="ret"></param>
        public void AddSqlCache(string cmd, List <object> ret)
        {
            sqlResultCacheMap[cmd] = ret;

            BDebug.Log("【添加缓存】 " + cmd);
        }
Exemplo n.º 13
0
        /// <summary>
        /// 核心功能,所有任务靠这个推进度
        /// 执行下个任务
        /// </summary>
        void DoNextTask()
        {
            if (isDoing)
            {
                return;
            }

            //没有东西的时候 跳出
            if (currentTaskGroup == null && this.allTaskList.Count == 0)
            {
                BDebug.Log("---------无任务组,退出----------");
                return;
            }
            else if (currentTaskGroup == null && this.allTaskList.Count > 0)
            {
                BDebug.Log("---------开始执行任务组----------");
                currentTaskGroup = this.allTaskList[0];
            }

            LoadTask task = null;

            //获取一个任务
            for (;;)
            {
                task = currentTaskGroup.GetTask();
                //task为空,或者任务可以执行,跳出
                if (task == null || willDoTaskSet.Contains(task.Id))
                {
                    break;
                }
            }


            //当前任务组已经全部完成
            if (task == null)
            {
                BDebug.Log("---------一组加载任务组已完成----------");
                currentTaskGroup = null;
                this.allTaskList.RemoveAt(0);

                DoNextTask();
            }
            else
            {
                //
                BDebug.Log("执行任务组中task:" + task.Id + " - " + task.ResourcePath);
                isDoing = true;
                //执行任务
                AsyncLoadAssetBundle(task.ResourcePath, b =>
                {
                    //移除任务
                    this.willDoTaskSet.Remove(task.Id);
                    //
                    var path = "assets/resource/runtime/" + task.ResourcePath.ToLower() + ".";
                    path     = GetExistPath(path);
                    var obj  = LoadFormAssetBundle <Object>(IPath.Combine(this.artRootPath, path), path);
                    //任务完成
                    currentTaskGroup.OnOneTaskComplete(task.Id, task.ResourcePath, obj);
                    isDoing = false;
                    //继续执行
                    DoNextTask();
                });
            }
        }
Exemplo n.º 14
0
 public void Do()
 {
     BDebug.Log("这是demo1的 log", "red");
 }
Exemplo n.º 15
0
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="source"></param>
        /// <param name="copyto"></param>
        /// <returns></returns>
        static IEnumerator IE_LoadScript(string root, HotfixCodeRunMode mode)
        {
            string dllPath = "";

            if (Application.isEditor)
            {
                dllPath = root + "/" + BApplication.GetPlatformPath(Application.platform) + DLLPATH;
            }
            else
            {
                //这里情况比较复杂,Mobile上基本认为Persistent才支持File操作,
                //可寻址目录也只有 StreamingAsset
                var firstPath  = Application.persistentDataPath + "/" + BApplication.GetPlatformPath(Application.platform) + DLLPATH;
                var secondPath = Application.streamingAssetsPath + "/" + BApplication.GetPlatformPath(Application.platform) + DLLPATH;
                if (!File.Exists(firstPath))
                {
                    var www = new WWW(secondPath);
                    yield return(www);

                    if (www.isDone && www.error == null)
                    {
                        BDebug.Log("拷贝dll成功:" + firstPath);
                        FileHelper.WriteAllBytes(firstPath, www.bytes);
                    }
                    else
                    {
                        BDebug.Log(www.error + "\n 拷贝dll失败:" + secondPath);
                    }
                }

                dllPath = firstPath;
            }


            //反射执行
            if (mode == HotfixCodeRunMode.ByReflection)
            {
                BDebug.Log("Dll路径:" + dllPath, "red");
                var bytes = File.ReadAllBytes(dllPath);
                var mdb   = dllPath + ".mdb";
                if (File.Exists(mdb))
                {
                    var bytes2 = File.ReadAllBytes(mdb);
                    Assembly = Assembly.Load(bytes, bytes2);
                }
                else
                {
                    Assembly = Assembly.Load(bytes);
                }

                BDebug.Log("代码加载成功,开始执行Start");
                var type   = Assembly.GetType("BDLauncherBridge");
                var method = type.GetMethod("Start", BindingFlags.Public | BindingFlags.Static);
                method.Invoke(null, new object[] { false, true });
            }
            //解释执行
            else if (mode == HotfixCodeRunMode.ByILRuntime)
            {
                BDebug.Log("Dll路径:" + dllPath, "red");
                //解释执行模式
                ILRuntimeHelper.LoadHotfix(dllPath);
                ILRuntimeHelper.AppDomain.Invoke("BDLauncherBridge", "Start", null, new object[] { true, false });
            }
            else
            {
                BDebug.Log("Dll路径:内置", "red");
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// 是否存在资源.并且校验hash
        /// </summary>
        /// <param name="platform"></param>
        /// <param name="serverAsset"></param>
        /// <returns></returns>
        static public bool IsExsitAssetWithCheckHash(RuntimePlatform platform, string assetName, string assetHash)
        {
            //本地是否下载过hash文件(之前下到一半就中止了),hash文件只会在
            var persistentHashPath = IPath.Combine(BApplication.persistentDataPath, BApplication.GetPlatformPath(platform), assetHash);

            if (File.Exists(persistentHashPath))
            {
                var hash = FileHelper.GetMurmurHash3(persistentHashPath);
                if (assetHash.Equals(hash))
                {
                    BDebug.Log($"hash文件存在 - {assetName} | hash - {assetHash}");
                    return(true);
                }
                else
                {
                    File.Delete(persistentHashPath);
                }
            }

            //persistent判断
            var persistentAssetPath = IPath.Combine(BApplication.persistentDataPath, BApplication.GetPlatformPath(platform), assetName);

            if (File.Exists(persistentAssetPath))
            {
                var hash = FileHelper.GetMurmurHash3(persistentAssetPath);
                if (assetHash.Equals(hash))
                {
                    BDebug.Log($"【AB校验】persistent存在 - {assetName} | hash - {assetHash}");
                    return(true);
                }
            }


            /************母包资源的判断*************/
            if (Application.isEditor && BDLauncher.Inst.GameConfig.ArtRoot == AssetLoadPathType.DevOpsPublish)
            {
                //devops
                var devopsAssetPath = IPath.Combine(BApplication.DevOpsPublishAssetsPath, BApplication.GetPlatformPath(platform), assetName);
                if (File.Exists(devopsAssetPath))
                {
                    var hash = FileHelper.GetMurmurHash3(devopsAssetPath);
                    if (assetHash.Equals(hash))
                    {
                        BDebug.Log($"【AB校验】devops存在 - {assetName} | hash - {assetHash}");
                        return(true);
                    }
                }
            }
            else
            {
                //Streaming 文件判断,无需Streaming前缀
                var streamingAssetPath = IPath.Combine(BApplication.GetPlatformPath(platform), assetName);
                if (BetterStreamingAssets.FileExists(streamingAssetPath))
                {
                    var bytes = BetterStreamingAssets.ReadAllBytes(streamingAssetPath);
                    var hash  = FileHelper.GetMurmurHash3(bytes);
                    if (assetHash.Equals(hash))
                    {
                        BDebug.Log($"【AB校验】streaming存在 - {assetName} | hash - {assetHash}");
                        return(true);
                    }
                }
            }


            return(false);
        }
Exemplo n.º 17
0
        /// <summary>
        /// initialize pomelo client
        /// </summary>
        /// <param name="host">server name or server ip (www.xxx.com/127.0.0.1/::1/localhost etc.)</param>
        /// <param name="port">server port</param>
        /// <param name="callback">socket successfully connected callback(in network thread)</param>
        public void initClient(string host, int port, Action callback = null)
        {
            timeoutEvent.Reset();
            eventManager = new EventManager();
            NetWorkChanged(NetWorkState.CONNECTING);

            IPAddress ipAddress;

            if (IPAddress.TryParse(host, out ipAddress) == false)
            {
                BDebug.Log("ip 解析失败");
            }
            else
            {
                //  BDebug.Log("ip 解析成功");
            }
            //  BDebug.Log("---------------0---------------");
            if (this.socket != null)
            {
                this.socket.Close();
            }
            this.socket   = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            this.disposed = false;
            //  BDebug.Log("---------------1---------------");
            IPEndPoint ie = new IPEndPoint(ipAddress, port);

            //  BDebug.Log("---------------2---------------");
            socket.BeginConnect(ie, new AsyncCallback((result) =>
            {
                try
                {
                    this.socket.EndConnect(result);
                    this.protocol = new Protocol(this, this.socket);
                    NetWorkChanged(NetWorkState.CONNECTED);

                    if (callback != null)
                    {
                        callback();
                    }
                }
                catch (SocketException e)
                {
                    Debug.LogError(e.Message);
                    if (netWorkState != NetWorkState.TIMEOUT)
                    {
                        NetWorkChanged(NetWorkState.ERROR);
                    }
                    Dispose();
                }
                finally
                {
                    timeoutEvent.Set();
                }
            }), this.socket);

            if (timeoutEvent.WaitOne(timeoutMSec, false))
            {
                if (netWorkState != NetWorkState.CONNECTED && netWorkState != NetWorkState.ERROR)
                {
                    NetWorkChanged(NetWorkState.TIMEOUT);
                    Dispose();
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// 开始任务
        /// </summary>
        /// <param name="serverConfigPath">服务器配置根目录</param>
        /// <param name="localConfigPath">本地根目录</param>
        /// <param name="onProcess"></param>
        /// <param name="onError"></param>
        /// 返回码: -1:error  0:success
        static private IEnumerator IE_Start(string serverConfigPath, string localConfigPath, Action <int, int> onProcess, Action <string> onError)
        {
            var platform = Utils.GetPlatformPath(Application.platform);

            if (curDownloadList == null || curDownloadList.Count == 0)
            {
                //开始下载服务器配置
                var serverPath = serverConfigPath + "/" + platform + "/" + platform + "_VersionConfig.json";
                BDebug.Log("server:" + serverPath);

                //下载config
                {
                    var wr = UnityWebRequest.Get(serverPath);
                    yield return(wr.SendWebRequest());

                    if (wr.error == null)
                    {
                        serverConfig = wr.downloadHandler.text;
                        BDebug.Log("服务器资源配置:" + serverConfig);
                    }
                    else
                    {
                        Debug.LogError(wr.error);
                    }
                }


                var         serverconf = LitJson.JsonMapper.ToObject <AssetConfig>(serverConfig);
                AssetConfig localconf  = null;
                var         localPath  = string.Format("{0}/{1}/{2}_VersionConfig.json", localConfigPath, platform, platform);

                if (File.Exists(localPath))
                {
                    localconf = LitJson.JsonMapper.ToObject <AssetConfig>(File.ReadAllText(localPath));
                }

                //对比差异列表进行下载
                curDownloadList = CompareConfig(localconf, serverconf);
                if (curDownloadList.Count > 0)
                {
                    //预通知要进入热更模式
                    onProcess(0, curDownloadList.Count);
                }
            }


            while (curDonloadIndex < curDownloadList.Count)
            {
                var item = curDownloadList[curDonloadIndex];

                var sp = serverConfigPath + "/" + platform + "/" + item.HashName;
                var lp = localConfigPath + "/" + platform + "/" + item.LocalPath;

                //创建目录
                var direct = Path.GetDirectoryName(lp);
                if (Directory.Exists(direct) == false)
                {
                    Directory.CreateDirectory(direct);
                }

                //下载
                var wr = UnityWebRequest.Get(sp);
                yield return(wr.SendWebRequest());

                if (wr.error == null)
                {
                    File.WriteAllBytes(lp, wr.downloadHandler.data);
                    BDebug.Log("下载成功:" + sp);
                    onProcess(curDonloadIndex, curDownloadList.Count - 1);
                }
                else
                {
                    BDebug.LogError("下载失败:" + wr.error);
                    onError(wr.error);
                    yield break;
                }

                //自增
                curDonloadIndex++;
            }

            //写到本地
            if (curDownloadList.Count > 0)
            {
                File.WriteAllText(string.Format("{0}/{1}/{2}_VersionConfig.json", localConfigPath, platform, platform), serverConfig);
            }
            else
            {
                BDebug.Log("不用更新");
                onProcess(1, 1);
            }


            //重置
            curDownloadList = null;
            curDonloadIndex = 0;
            serverConfig    = null;
        }
Exemplo n.º 19
0
    /// <summary>
    /// 编译DLL
    /// </summary>
    static public void GenDllByMono(string dataPath, string outPath)
    {
        EditorUtility.DisplayProgressBar("编译服务", "准备编译环境...", 0.1f);
        //base.dll 修改为 Assembly-CSharp,
        //为了保证依赖关系,在editor反射模式下能正常执行
        var baseDllPath = outPath + "/hotfix/Assembly-CSharp.dll";
        //输出环境
        var path = outPath + "/Hotfix";

        //创建临时环境
#if UNITY_EDITOR_OSX
        var tempDirect = Application.persistentDataPath + "/bd_temp";
#else
        var tempDirect = "c:/BD_temp";
#endif
        if (Directory.Exists(tempDirect))
        {
            Directory.Delete(tempDirect, true);
        }


        Directory.CreateDirectory(tempDirect);

        //建立目标目录
        var outDirectory = Path.GetDirectoryName(baseDllPath);
        //准备输出环境
        try
        {
            if (Directory.Exists(outDirectory))
            {
                Directory.Delete(path, true);
            }

            Directory.CreateDirectory(outDirectory);
        }
        catch (Exception e)
        {
            EditorUtility.ClearProgressBar();
            EditorUtility.DisplayDialog("提示", "Unity拒绝创建文件夹,请重试!", "OK");
            return;
        }


        #region 创建cs搜索目录

        EditorUtility.DisplayProgressBar("编译服务", "搜索待编译Code...", 0.2f);
        //
        List <string> searchPath = new List <string>()
        {
            "3rdPlugins", "Code", "Plugins", "Resource"
        };
        for (int i = 0; i < searchPath.Count; i++)
        {
            searchPath[i] = IPath.Combine(dataPath, searchPath[i]);
        }

        //2018.3的package目录
        var pPath = Application.dataPath.Replace("Assets", "") + "Library/PackageCache";
        searchPath.Add(pPath);

        List <string> csFiles = new List <string>();
        foreach (var s in searchPath)
        {
            var fs  = Directory.GetFiles(s, "*.cs*", SearchOption.AllDirectories).ToList();
            var _fs = fs.FindAll(f =>
            {
                if (!f.ToLower().Contains("editor")) //剔除editor
                {
                    return(true);
                }

                return(false);
            });

            csFiles.AddRange(_fs);
        }

        csFiles = csFiles.Distinct().ToList();
        for (int i = 0; i < csFiles.Count; i++)
        {
            csFiles[i] = csFiles[i].Replace('\\', '/').Trim();
        }

        EditorUtility.DisplayProgressBar("编译服务", "开始整理script", 0.2f);

        var baseCs   = csFiles.FindAll(f => !f.Contains("@hotfix") && f.EndsWith(".cs"));
        var hotfixCs = csFiles.FindAll(f => f.Contains("@hotfix") && f.EndsWith(".cs"));

        #endregion

        #region DLL引用搜集处理

        EditorUtility.DisplayProgressBar("编译服务", "收集依赖dll...", 0.3f);
        //这里是引入unity所有引用的dll

        var u3dExten  = EditorApplication.applicationContentsPath + @"/UnityExtensions/Unity";
        var u3dEngine = EditorApplication.applicationContentsPath + @"/Managed/UnityEngine";
        //var monoaot = EditorApplication.applicationContentsPath + @"/MonoBleedingEdge/lib/mono/unityjit";

        var dllPathList = new List <string>()
        {
            u3dExten, u3dEngine, dataPath
        };
        var dllFiles = new List <string>();
        //
        foreach (var p in dllPathList)
        {
            if (Directory.Exists(p) == false)
            {
                EditorUtility.DisplayDialog("提示", "u3d根目录不存在,请修改ScriptBiuld_Service类中,u3dui 和u3dengine 的dll目录", "OK");
                return;
            }
        }


        foreach (var dp in dllPathList)
        {
            var dlls = Directory.GetFiles(dp, "*.dll", SearchOption.AllDirectories);
            foreach (var d in dlls)
            {
                var dllAbsPath = d.Replace(dp, "");
                if (dllAbsPath.Contains("Editor") ||
                    dllAbsPath.Contains("iOS") ||
                    dllAbsPath.Contains("Android") ||
                    dllAbsPath.Contains("StreamingAssets"))
                {
                    continue;
                }

                dllFiles.Add(d);
            }
        }

        var monojit = EditorApplication.applicationContentsPath + @"/MonoBleedingEdge/lib/mono/unityjit";

        var _dlls = Directory.GetFiles(monojit, "*.dll", SearchOption.AllDirectories);

        var results = _dlls.ToList().FindAll((d) => d.Replace(monojit, "").Contains("Editor") == false &&
                                             d.Contains("System."));

        dllFiles.AddRange(results);
        //
        dllFiles = dllFiles.Distinct().ToList();
        //去除同名 重复的dll
        for (int i = 0; i < dllFiles.Count; i++)
        {
            var p = Path.GetFileName(dllFiles[i]);

            for (int j = dllFiles.Count - 1; j > i; j--)
            {
                if (Path.GetFileName(dllFiles[j]) == p)
                {
                    dllFiles.RemoveAt(j);
                }
            }
        }

        //拷贝dll
        for (int i = 0; i < dllFiles.Count; i++)
        {
            dllFiles[i] = dllFiles[i].Replace('\\', '/').Trim();
            //
            var copyto = IPath.Combine(tempDirect, i + ".dll"); //Path.GetFileName(dllFiles[i]));
            File.Copy(dllFiles[i], copyto, true);
            //File.WriteAllBytes(copyto,File.ReadAllBytes(dllFiles[i]));
            dllFiles[i] = copyto;
        }


        //添加系统依赖
        dllFiles.Add("mscorlib.dll");

        #endregion

        EditorUtility.DisplayProgressBar("编译服务", "复制到临时环境...", 0.4f);

        //全部拷贝到临时目录
        #region 为解决mono.exe error: 文件名太长问题

        int fileCounter = 1;
        csFilesMap = new Dictionary <int, string>();

        //拷贝 base cs
        for (int i = 0; i < baseCs.Count; i++)
        {
            var copyto = IPath.Combine(tempDirect, fileCounter + ".cs");
            //拷贝
            File.WriteAllText(copyto, File.ReadAllText(baseCs[i]));
            //保存文件索引
            csFilesMap[fileCounter] = baseCs[i];
            baseCs[i] = copyto.Replace("\\", "/");
            fileCounter++;
        }

        //拷贝 hotfix cs
        for (int i = 0; i < hotfixCs.Count; i++)
        {
            var copyto = IPath.Combine(tempDirect, fileCounter + ".cs");
            //拷贝
            File.WriteAllText(copyto, File.ReadAllText(hotfixCs[i]));
            //保存文件索引
            csFilesMap[fileCounter] = hotfixCs[i];
            //
            hotfixCs[i] = copyto.Replace("\\", "/");
            fileCounter++;
        }


        //检测dll
        for (int i = dllFiles.Count - 1; i >= 0; i--)
        {
            var r = dllFiles[i];
            if (File.Exists(r))
            {
                var fs = File.ReadAllBytes(r);
                try
                {
                    var assm = Assembly.Load(fs);
                }
                catch (Exception e)
                {
                    BDebug.Log("dll无效移除:" + r);
                    dllFiles.RemoveAt(i);
                }
            }
        }

        #endregion

        EditorUtility.DisplayProgressBar("编译服务", "[1/2]开始编译base.dll", 0.5f);
        //编译 base.dll
        try
        {
            Build(dllFiles.ToArray(), baseCs.ToArray(), baseDllPath);
        }
        catch (Exception e)
        {
            //EditorUtility.DisplayDialog("提示", "编译base.dll失败!", "OK");
            Debug.LogError(e.Message);
            EditorUtility.ClearProgressBar();
            return;
        }


        EditorUtility.DisplayProgressBar("编译服务", "[2/2]开始编译hotfix.dll", 0.7f);

        //将base.dll加入
        dllFiles.Add(baseDllPath);
        //编译hotfix.dll
        var outHotfixDirectory = outPath + "/hotfix/hotfix.dll";
        try
        {
            Build(dllFiles.ToArray(), hotfixCs.ToArray(), outHotfixDirectory);
        }
        catch (Exception e)
        {
            Debug.LogError(e.Message);
            EditorUtility.ClearProgressBar();
            return;
        }

        EditorUtility.DisplayProgressBar("编译服务", "清理临时文件", 0.9f);
        //删除临时目录
        Directory.Delete(tempDirect, true);
        //删除base.dll
        File.Delete(baseDllPath);
        EditorUtility.ClearProgressBar();

        AssetDatabase.Refresh();
    }
Exemplo n.º 20
0
    private void Awake()
    {
        Debug.Log("start bdframe");

        //组件加载
        this.gameObject.AddComponent <IEnumeratorTool>();
        this.gameObject.AddComponent <BResources>();
        Type[]      frameTypes = Assembly.GetExecutingAssembly().GetTypes();;
        Type[]      logicTypes = null;
        List <Type> allTypes   = new List <Type>();

        //编辑器环境下 寻找dll
        if (Application.isEditor)
        {
            Debug.Log("Edidor Get Types...");
            var assmblies    = new List <Assembly>(AppDomain.CurrentDomain.GetAssemblies());
            var logicAssmbly = assmblies.Find((a) => a.GetName().Name == "Assembly-CSharp");
            logicTypes = logicAssmbly.GetTypes();
        }

        allTypes.AddRange(frameTypes);
        allTypes.AddRange(logicTypes);
        //其他环境用热更模型进行加载

        //
        mgrList = new List <IMgr>();
        //寻找所有的管理器
        foreach (var t in allTypes)
        {
            if (t.BaseType != null && t.BaseType.GetInterface("IMgr") != null)
            {
                BDebug.Log("加载管理器-" + t, "green");
                var i = t.BaseType.GetProperty("Inst").GetValue(null, null) as  IMgr;
                mgrList.Add(i);
            }
            //游戏启动器
            else if (this.gameStart == null && t.GetInterface("IGameStart") != null)
            {
                gameStart = Activator.CreateInstance(t) as IGameStart;
            }
        }

        //类型注册
        foreach (var t in allTypes)
        {
            foreach (var iMgr in mgrList)
            {
                iMgr.CheckType(t);
            }
        }

        //管理器唤醒
        foreach (var _imgr in mgrList)
        {
            _imgr.Awake();
        }

        if (gameStart != null)
        {
            gameStart.Awake();
        }
    }
Exemplo n.º 21
0
    public override void Init()
    {
        base.Init();

        //增加覆盖测试
        var service = DataListenerServer.Create(nameof(DataListenerEnum));

        service.AddListener(DataListenerEnum.test, (o) =>
        {
            Debug.Log(o.ToString());
        });



        //demo1: screenview 切换
        //代码:
        //Game@hotfix/demo1
        this.btn_01.onClick.AddListener(() =>
        {
            ScreenViewManager.Inst.MainLayer.BeginNavTo(ScreenViewEnum.Demo1);
        });

        //demo4 : uflux窗口
        //代码:
        this.btn_04.onClick.AddListener(() =>
        {
            UIManager.Inst.LoadWindow(WinEnum.Win_Demo6);
            UIManager.Inst.ShowWindow(WinEnum.Win_Demo6);
        });


        //demo5: sqlite 查询
        this.btn_05.onClick.AddListener(() =>
        {
            //单条件查询
            Debug.Log("普通查询:");
            var ds = SqliteHelper.DB.GetTableRuntime().Where("id = 1").ToSearch <Hero>();
            ds     = SqliteHelper.DB.GetTableRuntime().Where("id = {0}", 1).ToSearch <Hero>();
            foreach (var d in ds)
            {
                Debug.Log(JsonMapper.ToJson(d));
            }
            //多条件查询
            Debug.Log("多条件查询:");
            ds = SqliteHelper.DB.GetTableRuntime().Where("id > 1").Where("and id < 3").ToSearch <Hero>();
            foreach (var d in ds)
            {
                Debug.Log(JsonMapper.ToJson(d));
            }
            //批量查询
            Debug.Log("Where or 批量查询:");
            ds = SqliteHelper.DB.GetTableRuntime().WhereAnd("id", "=", 1, 2).ToSearch <Hero>();
            foreach (var d in ds)
            {
                Debug.Log(JsonMapper.ToJson(d));
            }
            //批量查询
            Debug.Log("Where and 批量查询:");
            ds = SqliteHelper.DB.GetTableRuntime().WhereOr("id", "=", 2, 3).ToSearch <Hero>();
            foreach (var d in ds)
            {
                Debug.Log(JsonMapper.ToJson(d));
            }
        });
        //demo6:资源加载
        this.btn_06.onClick.AddListener(() =>
        {
            List <GameObject> golist = new List <GameObject>();
            //1.同步加载
            var go    = BResources.Load <GameObject>("AssetTest/Cube");
            var load1 = GameObject.Instantiate(go);
            go        = BResources.Load <GameObject>("Test/Cube");
            var load2 = GameObject.Instantiate(go);
            go        = BResources.Load <GameObject>("AssetTest/Particle");
            var load3 = GameObject.Instantiate(go);

            golist.Add(load1);
            golist.Add(load2);
            golist.Add(load3);

            //2.异步加载单个
            var id = BResources.AsyncLoad <GameObject>("Test/Cube", (o) =>
            {
                var load4 = GameObject.Instantiate(o);
                golist.Add(load4);
            });

            //3.异步加载多个
            var list = new List <string>()
            {
                "AssetTest/Cube", "Test/Cube"
            };
            BResources.AsyncLoad(list,
                                 (i, i2) =>
            {
                Debug.Log(string.Format("进度 {0} / {1}", i, i2));
            },
                                 (map) =>
            {
                BDebug.Log("加载全部完成,资源列表:");
                foreach (var r in map)
                {
                    BDebug.Log(string.Format("--> {0} : {1}", r.Key, r.Value.name));
                    var _go = GameObject.Instantiate(r.Value) as GameObject;
                    golist.Add(_go);
                }
            });


            IEnumeratorTool.WaitingForExec(5, () =>
            {
                foreach (var _go in golist)
                {
                    GameObject.Destroy(_go);
                }
            });
        });

        //代码:
        //Game@hotfix/demo_Manager_AutoRegister_And_Event
        this.btn_07.onClick.AddListener(() =>
        {
            var path = Application.persistentDataPath;

            VersionContorller.Start(UpdateMode.Repair, "http://127.0.0.1", path,
                                    (i, j) => { Debug.LogFormat("资源更新进度:{0}/{1}", i, j); },
                                    (error) => { Debug.LogError("错误:" + error); });
        });


        //发送消息机制
        this.btn_08.onClick.AddListener(() => { DemoEventManager.Inst.Do(DemoEventEnum.TestEvent2); });

        //图集
        this.btn_09.onClick.AddListener(() =>
        {
            UIManager.Inst.CloseWindow(WinEnum.Win_Main);
            UIManager.Inst.LoadWindow(WinEnum.Win_Demo5_Atlas);
            UIManager.Inst.ShowWindow(WinEnum.Win_Demo5_Atlas);
        });


        //数据监听
        this.btn_10.onClick.AddListener(() =>
        {
            UIManager.Inst.LoadWindow(WinEnum.Win_Demo_Datalistener);
            UIManager.Inst.ShowWindow(WinEnum.Win_Demo_Datalistener);
        });
    }
Exemplo n.º 22
0
    /// <summary>
    /// 这里注册整个游戏类型
    /// </summary>
    /// <param name="isILRMode"></param>
    static public void Start(bool isILRMode = false, bool isRefMode = false)
    {
        BDebug.Log("解释执行:" + isILRMode, "yellow");
        //组件加载
        List <Type> allTypes = new List <Type>();

        //编辑器环境下 寻找dll
        if (isILRMode)
        {
            allTypes = ILRuntimeHelper.GetHotfixTypes();
        }
        else
        {
            //获取DLL ALLtype
            var assembly = Assembly.GetAssembly(typeof(BDLauncherBridge));
            if (assembly == null)
            {
                Debug.Log("当前dll is null");
            }

            allTypes = assembly.GetTypes().ToList();
        }

        //
        var mgrs = new List <IMgr>();

        var gsaType = typeof(GameStartAtrribute);

        //寻找所有的管理器
        allTypes = allTypes.Distinct().ToList();
        foreach (var t in allTypes)
        {
            if (t != null &&
                t.BaseType != null &&
                t.BaseType.FullName != null &&
                t.BaseType.FullName.Contains(".ManagerBase`2"))
            {
                BDebug.Log("加载管理器-" + t, "green");
                var i = t.BaseType.GetProperty("Inst").GetValue(null, null) as IMgr;
                mgrs.Add(i);
                continue;
            }

            //游戏启动器
            //这里主要寻找
            if (hotfixStart == null)
            {
                var attrs = t.GetCustomAttributes(gsaType, false);
                if (attrs.Length > 0 &&
                    attrs[0] is GameStartAtrribute &&
                    ((GameStartAtrribute)attrs[0]).Index == 1)
                {
                    hotfixStart = Activator.CreateInstance(t) as IGameStart;
                }
            }
        }



        //类型注册
        foreach (var t in allTypes)
        {
            foreach (var iMgr in mgrs)
            {
                iMgr.CheckType(t);
            }
        }

        //管理器初始化
        foreach (var m in mgrs)
        {
            m.Init();
        }

        //gamestart生命注册
        if (hotfixStart != null)
        {
            hotfixStart.Start();
            BDLauncher.OnUpdate     = hotfixStart.Update;
            BDLauncher.OnLateUpdate = hotfixStart.LateUpdate;
        }
        //执行框架初始化完成的测试
        BDLauncher.OnBDFrameInitialized?.Invoke();
        BDLauncher.OnBDFrameInitializedForTest?.Invoke();
        //所有管理器开始工作
        foreach (var m in mgrs)
        {
            m.Start();
        }


        IEnumeratorTool.WaitingForExec(5, () =>
        {
            //执行单元测试
            if (BDLauncher.Inst.GameConfig.IsExcuteHotfixUnitTest && ILRuntimeHelper.IsRunning)
            {
                HotfixTestRunner.RunHotfixUnitTest();
            }
        });
    }
Exemplo n.º 23
0
 public static void SetLocalPath(string path)
 {
     BDebug.Log(string.Format("设置加载路径为:{0}", path));
     mAssetBundleMgr.LocalHotUpdateResPath = path;
 }
Exemplo n.º 24
0
    private static void SineAllResABName(string[] paths)
    {
        foreach (var path in paths)
        {
            var   _path = path.Replace("\\", "/");
            float val   = m_curIndex * 1.0f / paths.Length;
            EditorUtility.DisplayProgressBar("Updating", "Packaging, " + Path.GetFileNameWithoutExtension(_path) + "please wait..." + val * 100 + "%", val);
            m_curIndex++;
            var dependsource = "Assets" + _path.Replace(Application.dataPath, "");
            BDebug.Log("-----------------------------------------");
            BDebug.Log("source:" + dependsource);
            BDebug.Log("path:" + _path);

            string[] allDependObjectPaths = AssetDatabase.GetDependencies(dependsource);
            for (int i = 0; i < allDependObjectPaths.Length; i++)
            {
                var dependPath = allDependObjectPaths[i];
                BDebug.Log("depend on:" + dependPath);

                AssetImporter ai = AssetImporter.GetAtPath(dependPath);
                if (ai == null)
                {
                    BDebug.Log("not find Resource " + dependPath);
                    continue;
                }

                //重新组建ab名字,带上路径名
                dependPath = Path.GetFullPath(dependPath);
                dependPath = dependPath.Replace("\\", "/");
                var    temp      = dependPath.Split('/');
                string derictory = "";
                bool   isAdd     = false;
                foreach (var s in temp)
                {
                    if (isAdd)
                    {
                        if (derictory == "")
                        {
                            derictory = s;
                        }
                        else
                        {
                            derictory = derictory + "-" + s;
                        }
                    }
                    else if (s.Equals("Resources") || s.Equals("resources"))
                    {
                        isAdd = true;
                    }
                }
                //不在resource内部
                if (isAdd == false)
                {
                    foreach (var s in temp)
                    {
                        if (isAdd)
                        {
                            if (derictory == "")
                            {
                                derictory = s;
                            }
                            else
                            {
                                derictory = derictory + "-" + s;
                            }
                        }
                        else if (s.Equals("ArtRes"))
                        {
                            isAdd = true;
                        }
                    }
                }
                derictory             = derictory.Replace(".", "+");
                ai.assetBundleName    = derictory;
                ai.assetBundleVariant = "";
            }
        }
    }
Exemplo n.º 25
0
 protected virtual void OnDestroy()
 {
     BDebug.Log(debugType, "Destroying Physics World");
     Dispose(false);
 }
Exemplo n.º 26
0
    /// <summary>
    /// 这里注册整个游戏类型
    /// </summary>
    /// <param name="isILRMode"></param>
    static public void Start(bool isILRMode = false, bool isRefMode = false)
    {
        BDebug.Log("解释执行:" + isILRMode, "yellow");
        //组件加载
        List <Type> allTypes = new List <Type>();

        //编辑器环境下 寻找dll
        if (isILRMode)
        {
            var values = ILRuntimeHelper.AppDomain.LoadedTypes.Values.ToList();
            foreach (var v in values)
            {
                allTypes.Add(v.ReflectionType);
            }
        }
        else
        {
            //获取DLL ALLtype
            var assembly = Assembly.GetAssembly(typeof(BDLauncherBridge));
            if (assembly == null)
            {
                Debug.Log("当前dll is null");
            }

            allTypes = assembly.GetTypes().ToList();
        }

        //
        var mgrs = new List <IMgr>();

        var gsaType = typeof(GameStartAtrribute);

        //寻找所有的管理器
        allTypes = allTypes.Distinct().ToList();
        foreach (var t in allTypes)
        {
            if (t != null && t.BaseType != null && t.BaseType.FullName != null &&
                t.BaseType.FullName.Contains(".ManagerBase`2"))
            {
                BDebug.Log("加载管理器-" + t, "green");
                var i = t.BaseType.GetProperty("Inst").GetValue(null, null) as IMgr;
                mgrs.Add(i);
                continue;
            }

            //游戏启动器
            //这里主要寻找
            if ((isILRMode || isRefMode) && hotfixStart == null)
            {
                var attrs = t.GetCustomAttributes(gsaType, false);
                if (attrs.Length > 0)
                {
                    if (attrs[0] is GameStartAtrribute)
                    {
                        hotfixStart = Activator.CreateInstance(t) as IGameStart;
                        BDebug.Log("找到hotfix启动器 :" + t.FullName, "red");
                    }
                }
            }
        }

        BDebug.Log("管理器数量 =" + mgrs.Count);
        //类型注册
        foreach (var t in allTypes)
        {
            foreach (var iMgr in mgrs)
            {
                iMgr.CheckType(t);
            }
        }

        //管理器初始化
        foreach (var m in mgrs)
        {
            m.Init();
        }

        //game生命注册
        if (hotfixStart != null)
        {
            hotfixStart.Start();
            BDLauncher.OnUpdate     = hotfixStart.Update;
            BDLauncher.OnLateUpdate = hotfixStart.LateUpdate;
        }

        //所有管理器开始工作
        foreach (var m in mgrs)
        {
            m.Start();
        }

        BDebug.Log("管理器开始工作!");
    }
Exemplo n.º 27
0
    /// <summary>
    /// 整个游戏的启动器
    /// </summary>
    /// <param name="mainProjectTypes">游戏逻辑域传过来的所有type</param>
    static public void Start(Type[] mainProjectTypes = null, Type[] hotfixTypes = null)
    {
        //获取DLL ALLtype
        if (hotfixTypes == null)
        {
            if (Application.isEditor)
            {
                hotfixTypes = mainProjectTypes;
            }
        }


        //UI组件类型注册
        List <Type> types = new List <Type>();

        types.AddRange(typeof(Button).Assembly.GetTypes());  //Unity
        types.AddRange(typeof(IButton).Assembly.GetTypes()); //BDFramework.component
        types.AddRange(mainProjectTypes);                    //游戏业务逻辑
        if (Application.isEditor)
        {
            types = types.Distinct().ToList();
        }

        var uitype = typeof(UIBehaviour);

        foreach (var type in types)
        {
            //注册所有uiComponent
            bool ret = type.IsSubclassOf(uitype);
            if (ret)
            {
                if (!ILRuntimeHelper.UIComponentTypes.ContainsKey(type.Name))
                {
                    //因为Attribute typeof(Type)后无法获取fullname
                    ILRuntimeHelper.UIComponentTypes[type.FullName] = type;
                }
                else
                {
                    BDebug.LogError("有重名UI组件,请注意" + type.FullName);
                }
            }
        }

        //管理器列表
        var mgrList = new List <IMgr>();

        foreach (var type in hotfixTypes)
        {
            if (type != null &&
                type.BaseType != null &&
                type.BaseType.FullName != null)
            {
                if (type.BaseType.FullName.Contains(".ManagerBase`2")) //这里ILR里面只能这么做,丑但有效
                {
                    BDebug.Log("加载管理器-" + type, "green");
                    var i = type.BaseType.GetProperty("Inst").GetValue(null, null) as IMgr;
                    mgrList.Add(i);
                }
                else
                {
                    // 2.游戏启动器
                    if (hotfixStart == null)
                    {
                        if (type.IsClass && type.GetInterface(nameof(IHotfixGameStart)) != null)
                        {
                            hotfixStart = Activator.CreateInstance(type) as IHotfixGameStart;
                        }
                    }
                }
            }
        }

        //遍历type执行逻辑
        foreach (var type in hotfixTypes)
        {
            var mgrAttribute = type.GetAttributeInILRuntime <ManagerAttribute>();
            if (mgrAttribute == null)
            {
                continue;
            }

            //1.类型注册到管理器
            foreach (var iMgr in mgrList)
            {
                iMgr.CheckType(type, mgrAttribute);
            }
        }


        //管理器初始化
        foreach (var m in mgrList)
        {
            m.Init();
        }

        //gamestart生命注册
        if (hotfixStart != null)
        {
            hotfixStart.Start();
            BDLauncher.OnUpdate     += hotfixStart.Update;
            BDLauncher.OnLateUpdate += hotfixStart.LateUpdate;
        }

        //执行框架初始化完成的测试
        BDLauncher.OnBDFrameInitialized?.Invoke();
        BDLauncher.OnBDFrameInitializedForTest?.Invoke();
        //所有管理器开始工作
        foreach (var m in mgrList)
        {
            m.Start();
        }


        // IEnumeratorTool.WaitingForExec(5, () =>
        // {
        //     //执行单元测试
        //     if (BDLauncher.Inst.GameConfig.IsExcuteHotfixUnitTest && ILRuntimeHelper.IsRunning)
        //     {
        //         HotfixTestRunner.RunHotfixUnitTest();
        //     }
        // });
    }
Exemplo n.º 28
0
    public override void Init()
    {
        base.Init();

        //提示
//        var isCodeHotfix = GameObject.Find("BDFrame").GetComponent<BDLauncher>().IsCodeHotfix;
//        text_hotfixState.text = isCodeHotfix ? "热更模式:开" : "热更模式:关";

        //demo1: screenview 切换
        //代码:
        //Game@hotfix/demo1
        this.btn_01.onClick.AddListener(() => { ScreenViewManager.Inst.MainLayer.BeginNavTo(ScreenViewEnum.Demo1); });

        //demo2: ui window基本操作
        //代码:
        //Game@hotfix/demo2
        this.btn_02.onClick.AddListener(() =>
        {
            ScreenViewManager.Inst.MainLayer.BeginNavTo(ScreenViewEnum.Demo2);

            //向demo2窗口发消息
            var d = WindowData.Create("rotation");
            d.AddData("rotation", UnityEngine.Random.Range(-359, 359));
            UIManager.Inst.SendMessage((int)WinEnum.Win_Demo2, d);
        });

        //demo3: uitools使用
        //代码:
        //Game@hotfix/demo4
        this.btn_03.onClick.AddListener(() =>
        {
            UIManager.Inst.LoadWindows((int)WinEnum.Win_Demo4);
            UIManager.Inst.ShowWindow((int)WinEnum.Win_Demo4);
        });
        //demo4 : uflux窗口
        //代码:
        this.btn_04.onClick.AddListener(() =>
        {
            BDFramework.UFlux.UIManager.Inst.LoadWindow(UFluxWindowEnum.UFluxDemoMain);
            BDFramework.UFlux.UIManager.Inst.ShowWindow(UFluxWindowEnum.UFluxDemoMain);
        });


        //demo5: sqlite 查询
        this.btn_05.onClick.AddListener(() =>
        {
            var ds = SqliteHelper.DB.GetTableRuntime().Where("id > 1").ToSearch <Hero>();

            foreach (var d in ds)
            {
                Debug.Log(JsonMapper.ToJson(d));
            }
        });
        //demo6:资源加载
        this.btn_06.onClick.AddListener(() =>
        {
            //1.同步加载
            var go = BResources.Load <GameObject>("Test/Cube");
            GameObject.Instantiate(go).name = "load";

            //2.异步加载单个
            var id = BResources.AsyncLoad <GameObject>("Windows/window_demo1", (o) => { });

            //3.异步加载多个
            var list = new List <string>()
            {
                "Windows/window_demo1", "Windows/window_demo2"
            };
            BResources.AsyncLoad(list,
                                 (i, i2) => { Debug.Log(string.Format("进度 {0} / {1}", i, i2)); },
                                 (map) =>
            {
                BDebug.Log("加载全部完成,资源列表:");
                foreach (var r in map)
                {
                    BDebug.Log(string.Format("--> {0} : {1}", r.Key, r.Value.name));
                    GameObject.Instantiate(r.Value);
                }
            });
        });

        //代码:
        //Game@hotfix/demo_Manager_AutoRegister_And_Event
        this.btn_07.onClick.AddListener(() =>
        {
            var path = Application.persistentDataPath;

            VersionContorller.Start(UpdateMode.Repair, "http://127.0.0.1", path,
                                    (i, j) => { Debug.LogFormat("资源更新进度:{0}/{1}", i, j); },
                                    (error) => { Debug.LogError("错误:" + error); });
        });


        //发送消息机制
        this.btn_08.onClick.AddListener(() => { DemoEventManager.Inst.Do(DemoEventEnum.TestEvent2); });

        //图集
        this.btn_09.onClick.AddListener(() =>
        {
            UIManager.Inst.CloseWindow(WinEnum.Win_Main);
            UIManager.Inst.LoadWindows((int)WinEnum.Win_Demo5_Atlas);
            UIManager.Inst.ShowWindow((int)WinEnum.Win_Demo5_Atlas);
        });
    }
Exemplo n.º 29
0
        /// <summary>
        /// VC进行数据绑定
        /// </summary>
        /// <param name="viewControl"></param>
        /// <param name="view"></param>
        static private void BindEvnet(IViewControl viewControl, IView view)
        {
            //开始反射所有的UI组件,自动注册Ctrl下面 OnEvent_+ 字段名
            var viewType    = view.GetType();
            var controlType = viewControl.GetType();
            var vfields     = viewType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);

            foreach (var f in vfields)
            {
                if (!f.FieldType.IsSubclassOf(typeof(UnityEngine.Object)))
                {
                    continue;
                }
                //所有ui组件
                if (f.FieldType == typeof(Button))//主动注册OnClick、
                {
                    //
                    var fClick = controlType.GetMethod(string.Format("OnClick_{0}", f.Name), BindingFlags.Instance | BindingFlags.NonPublic);
                    if (fClick != null)
                    {
                        var o = f.GetValue(view) as Button;
                        o.onClick.AddListener(() =>
                        {
                            fClick.Invoke(viewControl, new object[] {});
                        });
                    }
                    else
                    {
                        BDebug.Log(string.Format("ui事件未实现:{0} - {1}", viewType.FullName, f.Name), "yellow");
                    }
                }
                else if (f.FieldType == typeof(Scrollbar))//主动注册OnValueChange
                {
                    var o            = f.GetValue(view) as Scrollbar;
                    var fValueChange = controlType.GetMethod(string.Format("OnValueChange_{0}", f.Name), BindingFlags.Instance | BindingFlags.NonPublic);
                    if (fValueChange != null)
                    {
                        o.onValueChanged.AddListener((value) =>
                        {
                            fValueChange.Invoke(viewControl, new object[] { value });
                        });
                    }
                    else
                    {
                        BDebug.Log(string.Format("ui事件未实现:{0} - {1}", viewType.FullName, f.Name), "yellow");
                    }
                }
                else if (f.FieldType == typeof(Slider)) //自动注册OnValueChange
                {
                    var o            = f.GetValue(view) as Slider;
                    var fValueChange = controlType.GetMethod(string.Format("OnValueChange_{0}", f.Name), BindingFlags.Instance | BindingFlags.NonPublic);
                    if (fValueChange != null)
                    {
                        o.onValueChanged.AddListener((value) =>
                        {
                            fValueChange.Invoke(viewControl, new object[] { value });
                        });
                    }
                    else
                    {
                        BDebug.Log(string.Format("ui事件未实现:{0} - {1}", viewType.FullName, f.Name), "yellow");
                    }
                }
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// 开始任务
        /// </summary>
        /// <param name="serverConfigPath">服务器配置根目录</param>
        /// <param name="localConfigPath">本地根目录</param>
        /// <param name="onProcess"></param>
        /// <param name="onError"></param>
        /// 返回码: -1:error  0:success
        static async public Task <int> Start(string serverConfigPath, string localConfigPath, Action <int, int> onProcess, Action <string> onError)
        {
            var client   = HttpMgr.Inst.GetFreeHttpClient();
            var platform = Utils.GetPlatformPath(Application.platform);
            //开始下载服务器配置
            var    serverPath   = serverConfigPath + "/" + platform + "/" + platform + "_VersionConfig.json";
            string serverConfig = "";

            try
            {
                serverConfig = await client.DownloadStringTaskAsync(serverPath);

                BDebug.Log("服务器资源配置:" + serverConfig);
            }
            catch (Exception e)
            {
                onError(e.Message);
                return(-1);
            }


            var         serverconf = LitJson.JsonMapper.ToObject <AssetConfig>(serverConfig);
            AssetConfig localconf  = null;
            var         localPath  = localConfigPath + "/" + platform + "/" + platform + "_VersionConfig.json";

            if (File.Exists(localPath))
            {
                localconf = LitJson.JsonMapper.ToObject <AssetConfig>(File.ReadAllText(localPath));
            }

            //对比差异列表进行下载
            var list = CompareConfig(localConfigPath, localconf, serverconf);

            if (list.Count > 0)
            {
                //预通知要进入热更模式
                onProcess(0, list.Count);
            }

            int count = 0;

            foreach (var item in list)
            {
                count++;
                var sp = serverConfigPath + "/" + platform + "/" + item.HashName;
                var lp = localConfigPath + "/" + platform + "/" + item.LocalPath;

                //创建目录
                var direct = Path.GetDirectoryName(lp);
                if (Directory.Exists(direct) == false)
                {
                    Directory.CreateDirectory(direct);
                }

                //下载
                try
                {
                    await client.DownloadFileTaskAsync(sp, lp);
                }
                catch (Exception e)
                {
                    BDebug.LogError(sp);
                    onError(e.Message);
                    return(-1);
                }

                BDebug.Log("下载成功:" + sp);
                onProcess(count, list.Count);
            }

            //写到本地
            if (list.Count > 0)
            {
                File.WriteAllText(localPath, serverConfig);
            }
            else
            {
                BDebug.Log("可更新数量为0");
            }

            return(0);
        }