Esempio n. 1
0
        public static async ETVoid OnLoginAsync(string account)
        {
            try
            {
                //  ===> 登录session
                Session   session  = Game.Scene.GetComponent <NetOuterComponent>().Create(GlobalConfigComponent.Instance.GlobalProto.Address);
                R2C_Login r2CLogin = (R2C_Login)await session.Call(new C2R_Login()
                {
                    Account = account, Password = "******"
                });

                // ===> 网关session
                Session gateSession = Game.Scene.GetComponent <NetOuterComponent>().Create(r2CLogin.Address);
                Game.Scene.AddComponent <SessionComponent>().Session = gateSession;


                G2C_LoginGate g2CLoginGate = (G2C_LoginGate)await SessionComponent.Instance.Session.Call(new C2G_LoginGate()
                {
                    Key = r2CLogin.Key
                });

                Log.Info("登陆gate成功!");

                // 创建Player
                Player          player          = ComponentFactory.CreateWithId <Player>(g2CLoginGate.PlayerId);
                PlayerComponent playerComponent = Game.Scene.GetComponent <PlayerComponent>();
                playerComponent.MyPlayer = player;

                Game.EventSystem.Run(EventIdType.LoginFinish);

                // 测试消息有成员是class类型
                //G2C_PlayerInfo g2CPlayerInfo = (G2C_PlayerInfo) await SessionComponent.Instance.Session.Call(new C2G_PlayerInfo());
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
Esempio n. 2
0
        public void Init(UIBattleMainData data)
        {
            matchModule  = UtilsModuleManager.GetModule(ModuleType.MatchModule) as MatchModule;
            battleModule = UtilsModuleManager.GetModule(ModuleType.MatchModule) as MatchModule;
            funcs        = matchModule.matchInit.funcs;
            myRunData    = matchModule.myRunData;
            uiData       = data;

            timeCountDown = ComponentFactory.Create <TimeCountDownComponent>();
            endPos        = funcs.GetEnd();
            SetMyPosTo2D();

            if (battleModule.IsPlayback)
            {
                uiData.recttrans_m_GroundState.localPosition -= new Vector3(52, 0, 0);
            }
            //preEnsureValue = 0;
            //preSpeedValue = 0;

            //uiData.slider_m_SpeedProgress.value = 1f;
            //uiData.slider_SliderEnsure.value = 1f;
            uiData.toggle_ToggleName.onValueChanged.AddListener(OnToggleSwitchHeadClick);
        }
Esempio n. 3
0
 //如果数据库没有签到奖励列表就初始化
 public async void SaveInitDefaultSignInAwardList()
 {
     for (int i = 0; i < 7; i++)
     {
         SignInAward signInAward = ComponentFactory.Create <SignInAward>();
         if (i < 3)
         {
             signInAward.Amount = 2;
         }
         else if (i < 6)
         {
             signInAward.Amount = i;
         }
         else
         {
             signInAward.Amount = 10;
         }
         signInAward.GoodsId    = GoodsId.Jewel;
         signInAward.NumberDays = i + 1;
         mSignInAwardList.Add(signInAward);
         await dbProxyComponent.Save(signInAward);
     }
 }
Esempio n. 4
0
 //每小局要清空的数据
 public void LittleRoundClearData()
 {
     ResidueCards = null;
     CanOperatePlayerIndex.Clear();//当前可以行进操作的玩家索引列表
     BeforeOperateResults.Clear();
     HuPaiPlayerSeatIndexs.Clear();
     LiangDaoCanHuCards.Clear();     //亮倒 所有玩家可以胡的牌
     CurrChuPaiIndex           = -1; //当前出牌玩家的索引
     CurrChuPaiCard            = -1; //当前出的哪张牌
     IsDaPiaoBeing             = false;
     EntiretyOprationAleadyNum = 0;
     LastMoPaiSeatIndex        = -1; //最后一个摸牌玩家的索引
     CanPlayCardPlayerIndex    = 0;  //正在操作的玩家索引
     QiOperateNextStep         = 0;
     _overTime = 0;
     CurrParticularMiltaryRecordData = ComponentFactory.Create <ParticularMiltaryRecordDataInfo>(); //重置录像小局数据
     EndCanOperateAndCanChuMessage   = null;                                                        //最后一条可操作消息清除
     MaiMaCard = -1;                                                                                //买马买的哪一张牌
     foreach (var player in FiveStarPlayerDic)
     {
         player.Value.LittleRoundClearData();
     }
 }
Esempio n. 5
0
        public async Task <UI> CreateAsync(Scene scene, string type, GameObject parent)
        {
            try
            {
                UnityEngine.Object obj = await ResourcesHelper.LoadAsync("KV");

                GameObject bundleGameObject = ((GameObject)obj).Get <GameObject>(type);
                GameObject go = UnityEngine.Object.Instantiate(bundleGameObject);
                go.layer = LayerMask.NameToLayer(LayerNames.UI);
                UI ui = ComponentFactory.Create <UI, GameObject>(go);

                ui.AddUIBaseComponent <UIDialogComponent>();

                AddSubComponent(ui);

                return(ui);
            }
            catch (Exception e)
            {
                Log.Error(e);
                return(null);
            }
        }
Esempio n. 6
0
        private async void InsertAreaData()
        {
            List <ComponentWithId> areaInfoList = new List <ComponentWithId>();

            try
            {
                AreaInfo DDZArea = ComponentFactory.Create <AreaInfo, int>(101);
                DDZArea.GameId = 1; DDZArea.AreaId = 101; DDZArea.AreaType = "初级场"; DDZArea.Score = 1;
                areaInfoList.Add(DDZArea);

                DBProxyComponent dbProxy = Game.Scene.GetComponent <DBProxyComponent>();

                await DBSaveHelper.SaveBatch(dbProxy, areaInfoList);

                Log.Debug("向数据库插入场数据成功  !!!");

                DBHelper <AreaInfo> .QureySingleTableAllData("AreaInfo", areaList);
            }
            catch (System.Exception e)
            {
                Log.Debug($"插入游戏列表失败 信息 {e}!!!");
            }
        }
Esempio n. 7
0
        private async void InsertAreaData()
        {
            List <ComponentWithId> roomInfoList = new List <ComponentWithId>();

            try
            {
                int      DouDiZhuRoomId = RandomHelper.RandInt32();
                RoomInfo DouDiZhuRoom   = ComponentFactory.Create <RoomInfo, int>(DouDiZhuRoomId);
                DouDiZhuRoom.GameId   = 1; DouDiZhuRoom.AreaId = 101; DouDiZhuRoom.RoomId = DouDiZhuRoomId; DouDiZhuRoom.DiFen = 1;
                DouDiZhuRoom.MaxCount = 3;
                roomInfoList.Add(DouDiZhuRoom);

                DBProxyComponent dbProxy = Game.Scene.GetComponent <DBProxyComponent>();

                await DBSaveHelper.SaveBatch(dbProxy, roomInfoList);

                Log.Debug("向数据库插入 房间数据成功  !!!");
                DBHelper <RoomInfo> .QureySingleTableAllData("RoomInfo", roomList);
            }
            catch (Exception e)
            {
                Log.Debug($"插入游戏列表失败 信息 {e}!!!");
            }
        }
Esempio n. 8
0
        /// <summary>
        /// 获取远程版本文件
        /// </summary>
        /// <returns></returns>
        public static async ETTask <VersionConfig> GetRemoteVersion()
        {
            VersionConfig remoteVersionConfig;

            string versionUrl = GlobalConfigComponent.Instance.GlobalProto.GetUrl() + "StreamingAssets/" + "Version.txt";

            try
            {
                using (UnityWebRequestAsync webRequestAsync = ComponentFactory.Create <UnityWebRequestAsync>())
                {
                    await webRequestAsync.DownloadAsync(versionUrl);

                    remoteVersionConfig = JsonHelper.FromJson <VersionConfig>(webRequestAsync.Request.downloadHandler.text);
                }
            }
            catch (Exception e)
            {
                Log.Error($"download version.txt error:{e}");

                throw;
            }

            return(remoteVersionConfig);
        }
Esempio n. 9
0
        private async Task LoadAllAssests(string assetBundleName, AssetBundle assetBundle)
        {
            if (!Define.isUseAssetBundle)
            {
#if UNITY_EDITOR
                var realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
                foreach (string s in realPath)
                {
                    string             assetName = Path.GetFileNameWithoutExtension(s);
                    string             path      = $"{assetBundleName}/{assetName}".ToLower();
                    UnityEngine.Object resource  = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(s);
                    ABManager.resourceCache[path] = resource;
                }
#endif
                return;
            }
            if (assetBundle == null)
            {
                ZLog.Error($"{assetBundleName} is Null?");
                return;
            }
            if (!assetBundle.isStreamedSceneAssetBundle)
            {
                // 异步load资源到内存cache住
                UnityEngine.Object[] assets;
                using (AssetsLoaderAsync assetsLoaderAsync = ComponentFactory.Create <AssetsLoaderAsync, AssetBundle>(assetBundle))
                {
                    assets = await assetsLoaderAsync.LoadAllAssetsAsync();
                }
                foreach (UnityEngine.Object asset in assets)
                {
                    string path = $"{assetBundleName}/{asset.name}".ToLower();
                    ABManager.resourceCache[path] = asset;
                }
            }
        }
Esempio n. 10
0
        /// <summary>
        /// 创建一个新Session
        /// </summary>
        public virtual Session Create(IPEndPoint ipEndPoint)
        {
            try
            {
                AChannel channel = this.Service.ConnectChannel(ipEndPoint);
                Session  session = ComponentFactory.CreateWithId <Session, NetworkComponent, AChannel>(IdGenerater.GenerateId(), this, channel);
                session.Parent         = this;
                channel.ErrorCallback += (c, e) =>
                {
                    session.Error = e;
                    this.Remove(session.Id);
                };

                channel.ReadCallback += (packet) => { session.OnRead(packet); };

                this.sessions.Add(session.Id, session);
                return(session);
            }
            catch (Exception e)
            {
                Log.Error(e);
                return(null);
            }
        }
        public async ETTask StartAsync()
        {
            // 获取远程的Version.txt
            string versionUrl = "";

            try
            {
                using (UnityWebRequestAsync webRequestAsync = ComponentFactory.Create <UnityWebRequestAsync>())
                {
                    //UnityWebRequest UnityWebRequest www下载
                    versionUrl = GlobalConfigComponent.Instance.GlobalProto.GetUrl() + "StreamingAssets/" + "Version.txt";
                    //Log.Debug(versionUrl);
                    await webRequestAsync.DownloadAsync(versionUrl);

                    remoteVersionConfig = JsonHelper.FromJson <VersionConfig>(webRequestAsync.Request.downloadHandler.text);
                    //Log.Debug(JsonHelper.ToJson(this.VersionConfig));
                }
            }
            catch (Exception e)
            {
                throw new Exception($"url: {versionUrl}", e);
            }

            // 获取streaming目录的Version.txt
            VersionConfig streamingVersionConfig;
            string        versionPath = Path.Combine(PathHelper.AppResPath4Web, "Version.txt");

            using (UnityWebRequestAsync request = ComponentFactory.Create <UnityWebRequestAsync>())
            {
                await request.DownloadAsync(versionPath);

                streamingVersionConfig = JsonHelper.FromJson <VersionConfig>(request.Request.downloadHandler.text);
            }

            // 删掉远程不存在的文件
            DirectoryInfo directoryInfo = new DirectoryInfo(PathHelper.AppHotfixResPath);

            //如果存放热更新资源的文件夹存在
            if (directoryInfo.Exists)
            {
                //获取到里面的所有子文件
                FileInfo[] fileInfos = directoryInfo.GetFiles();
                foreach (FileInfo fileInfo in fileInfos)
                {
                    //就是远程下载下来的版本文件 json反序列化成一个实体类 FileInfoDict这个字典就包含了所有AB文件信息
                    if (remoteVersionConfig.FileInfoDict.ContainsKey(fileInfo.Name))
                    {
                        continue;
                    }

                    if (fileInfo.Name == "Version.txt")
                    {
                        continue;
                    }
                    //为什么要删除掉远程不存在的文件呢 主要是为了避免加载资源出错 资源重复 会导致到报错
                    fileInfo.Delete();
                }
            }
            //如果保存热更新资源的文件夹不存在的话 通过Create进行创建
            else
            {
                directoryInfo.Create();
            }

            // 对比MD5
            foreach (FileVersionInfo fileVersionInfo in remoteVersionConfig.FileInfoDict.Values)
            {
                // 对比md5 跟我们本地的文件进行MD5对比
                string localFileMD5 = BundleHelper.GetBundleMD5(streamingVersionConfig, fileVersionInfo.File);
                //如果相等 就忽略 表示两个版本中 这个文件并未做任何改动
                if (fileVersionInfo.MD5 == localFileMD5)
                {
                    continue;
                }
                //如果两个文件的MD5不一致 把要下载的文件 压入到队列
                this.bundles.Enqueue(fileVersionInfo.File);
                //下载的总大小也加上这个文件的大小
                this.TotalSize += fileVersionInfo.Size;
            }
        }
Esempio n. 12
0
        public static Tank Create(TankInfoFirstEnter firstInfo, Vector3 Pos, Vector3 Rot)
        {
            long id = firstInfo.TankFrameInfo.TankId;

            ResourcesComponent resourcesComponent = Game.Scene.GetComponent <ResourcesComponent>();
            //Game.Scene.GetComponent<ResourcesComponent>().LoadBundle($"Unit.unity3d");
            GameObject bundleGameObject = (GameObject)resourcesComponent.GetAsset(AssetBundleName.Unit, PrefabName.Unit);
            //Game.Scene.GetComponent<ResourcesComponent>().UnloadBundle($"Unit.unity3d");
            GameObject prefab = bundleGameObject.Get <GameObject>(PrefabName.Tank);

            TankComponent tankComponent = Game.Scene.GetComponent <TankComponent>();

            Tank tank = ComponentFactory.CreateWithId <Tank>(id);

            tank.GameObject = resourcesComponent.NewObj(PrefabType.Tank, prefab);

            tank.GameObject.transform.position = Pos;

            tank.GameObject.transform.eulerAngles = Rot;


            GameObject parent = GameObject.Find($"/Global/Unit");

            tank.GameObject.transform.SetParent(parent.transform, false);

            NumericComponent numericComponent = tank.AddComponent <NumericComponent>();

            tank.Name = firstInfo.Name;

            tank.TankCamp = firstInfo.TankCamp;

            if (id == 10000 || PlayerComponent.Instance.MyPlayer.TankId == id)
            {
                tank.TankType = TankType.Local;

                tank.AddComponent <TankMoveComponent>();

                tank.AddComponent <CameraComponent>();

                tank.AddComponent <TurretComponent>();

                // 子弹管理组件
                tank.AddComponent <BulletComponent>();

                // 发射子弹的组件
                tank.AddComponent <TankShootComponent>();

                tank.AddComponent <LocalTankComponent>();

                tankComponent.MyTank = tank;

                // 如果是自己设置层级为9,为了让坦克不打中自己

                Utility.ChangeLayer(tank.GameObject, LayerNames.OwnTank);

                tank.GameObject.layer = 9;
            }
            else
            {
                tank.TankType = TankType.Remote;

                tank.AddComponent <RemoteTankComponent>();

                tank.AddComponent <TurretComponent>();

                tank.AddComponent <TankShootComponent>();

                tank.AddComponent <BulletComponent>();

                tank.AddComponent <OverHeadComponent>();
            }



            tankComponent.Add(tank);

            // 先将坦克加入TankComponent再赋值,因为赋值的时候会触发事件,事件中可能要从TankComponent中取坦克
            numericComponent[NumericType.MaxHpBase] = firstInfo.MaxHpBase;

            numericComponent[NumericType.HpBase] = firstInfo.HpBase;

            numericComponent[NumericType.AtkBase] = firstInfo.AtkBase;

            return(tank);
        }
Esempio n. 13
0
        public async Task LoadOneBundleAsync(string assetBundleName)
        {
            ABInfo abInfo;

            if (this.bundles.TryGetValue(assetBundleName, out abInfo))
            {
                ++abInfo.RefCount;
                return;
            }


            if (this.cacheDictionary.ContainsKey(assetBundleName))
            {
                abInfo = this.cacheDictionary[assetBundleName];
                ++abInfo.RefCount;
                this.bundles[assetBundleName] = abInfo;
                this.cacheDictionary.Remove(assetBundleName);
                return;
            }


            if (!Define.IsAsync)
            {
#if UNITY_EDITOR
                string[] realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
                foreach (string s in realPath)
                {
                    string             assetName = Path.GetFileNameWithoutExtension(s);
                    string             path      = $"{assetBundleName}/{assetName}".ToLower();
                    UnityEngine.Object resource  = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(s);
                    this.resourceCache[path] = resource;
                }

                this.bundles[assetBundleName] = new ABInfo(assetBundleName, null);
                return;
#endif
            }

            AssetBundle assetBundle;
            using (AssetsBundleLoaderAsync assetsBundleLoaderAsync = ComponentFactory.Create <AssetsBundleLoaderAsync>())
            {
                assetBundle = await assetsBundleLoaderAsync.LoadAsync(assetBundleName);
            }

            if (!assetBundle.isStreamedSceneAssetBundle)
            {
                // 异步load资源到内存cache住
                UnityEngine.Object[] assets;
                using (AssetsLoaderAsync assetsLoaderAsync = ComponentFactory.Create <AssetsLoaderAsync, AssetBundle>(assetBundle))
                {
                    assets = await assetsLoaderAsync.LoadAllAssetsAsync();
                }
                foreach (UnityEngine.Object asset in assets)
                {
                    string path = $"{assetBundleName}/{asset.name}".ToLower();
                    this.resourceCache[path] = asset;
                }
            }

            this.bundles[assetBundleName] = new ABInfo(assetBundleName, assetBundle);
        }
Esempio n. 14
0
        public void LoadOneBundle(string assetBundleName)
        {
            //Log.Debug($"---------------load one bundle {assetBundleName}");
            ABInfo abInfo;

            if (this.bundles.TryGetValue(assetBundleName, out abInfo))
            {
                ++abInfo.RefCount;
                return;
            }

            if (!Define.IsAsync)
            {
                string[] realPath = null;
#if UNITY_EDITOR
                realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
                foreach (string s in realPath)
                {
                    string             assetName = Path.GetFileNameWithoutExtension(s);
                    UnityEngine.Object resource  = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(s);
                    AddResource(assetBundleName, assetName, resource);
                }

                abInfo        = ComponentFactory.CreateWithParent <ABInfo, string, AssetBundle>(this, assetBundleName, null);
                abInfo.Parent = this;
                this.bundles[assetBundleName] = abInfo;
#endif
                return;
            }
            string      p           = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
            AssetBundle assetBundle = null;
            TryABSecurity();
            if (File.Exists(p))
            {
                if (Define.IsAsync && Define.IsILRuntime && mABSecurity == 2)
                {
                    assetBundle = AssetBundle.LoadFromFile(p, 0, 128);
                }
                else
                {
                    assetBundle = AssetBundle.LoadFromFile(p);
                }
            }
            else
            {
                p = Path.Combine(PathHelper.AppResPath, assetBundleName);
                if (Define.IsAsync && Define.IsILRuntime && mABSecurity == 2)
                {
                    assetBundle = AssetBundle.LoadFromFile(p, 0, 128);
                }
                else
                {
                    assetBundle = AssetBundle.LoadFromFile(p);
                }
            }

            if (assetBundle == null)
            {
                throw new Exception($"assets bundle not found: {assetBundleName}");
            }

            if (!assetBundle.isStreamedSceneAssetBundle)
            {
                // 异步load资源到内存cache住
                UnityEngine.Object[] assets = assetBundle.LoadAllAssets();
                foreach (UnityEngine.Object asset in assets)
                {
                    AddResource(assetBundleName, asset.name, asset);
                }
            }

            abInfo = ComponentFactory.CreateWithParent <ABInfo, string, AssetBundle>(this, assetBundleName, assetBundle);
            this.bundles[assetBundleName] = abInfo;
        }
Esempio n. 15
0
        public static async ETVoid Login(string account, string password)
        {
            SekiaLoginComponent login = Game.Scene.GetComponent <FUIComponent>().Get(FUIType.SekiaLogin).GetComponent <SekiaLoginComponent>();

            Session         sessionRealm = Game.Scene.GetComponent <NetOuterComponent>().Create(GlobalConfigComponent.Instance.GlobalProto.Address);
            A0002_Login_R2C messageRealm = (A0002_Login_R2C)await sessionRealm.Call(new A0002_Login_C2R()
            {
                Account = account, Password = password
            });

            sessionRealm.Dispose();
            login.Prompt.GObject.asTextField.text = "正在登录中...";

            //判断Realm服务器返回结果
            if (messageRealm.Error == ErrorCode.ERR_AccountOrPasswordError)
            {
                login.Prompt.GObject.asTextField.text = "登录失败,账号或密码错误";
                login.AccountInput.Get("Input").GObject.asTextInput.text  = "";
                login.PasswordInput.Get("Input").GObject.asTextInput.text = "";
                login.isLogining = false;
                return;
            }
            //判断通过则登陆Realm成功

            //创建唯一Session
            Session sessionGate = Game.Scene.GetComponent <NetOuterComponent>().Create(messageRealm.GateAddress);

            if (SessionComponent.Instance == null)
            {
                //Log.Debug("创建唯一Session");
                Game.Scene.AddComponent <SessionComponent>().Session = sessionGate;
            }
            else
            {
                SessionComponent.Instance.Session = sessionGate;
            }

            A0003_LoginGate_G2C messageGate = (A0003_LoginGate_G2C)await sessionGate.Call(new A0003_LoginGate_C2G()
            {
                GateLoginKey = messageRealm.GateLoginKey
            });

            //判断登陆Gate服务器返回结果
            if (messageGate.Error == ErrorCode.ERR_ConnectGateKeyError)
            {
                login.Prompt.GObject.asTextField.text = "连接网关服务器超时";
                login.AccountInput.Get("Input").GObject.asTextInput.text  = "";
                login.PasswordInput.Get("Input").GObject.asTextInput.text = "";
                sessionGate.Dispose();
                login.isLogining = false;
                return;
            }
            //判断通过则登陆Gate成功

            login.Prompt.GObject.asTextField.text = "";
            User user = ComponentFactory.Create <User, long>(messageGate.UserID);

            GamerComponent.Instance.MyUser = user;
            //Log.Debug("登陆成功");

            //获取角色信息判断应该进入哪个界面
            A0008_GetUserInfo_G2C messageUser = (A0008_GetUserInfo_G2C)await sessionGate.Call(new A0008_GetUserInfo_C2G());

            //消息中包含了3个CharacterInfo

            //正常的角色等级为正整数
            if (messageUser.Characters.Count == 3 &&
                messageUser.Characters[0].Level == 0 &&
                messageUser.Characters[1].Level == 0 &&
                messageUser.Characters[2].Level == 0)
            {
                //进入创建角色界面
                CreateCharacterFactory.Create(messageUser);
                CreateCharacterComponent creater = Game.Scene.GetComponent <FUIComponent>().Get(FUIType.CreateCharacter).GetComponent <CreateCharacterComponent>();
                creater.Seat = 1; //创建第一个空位的角色
            }
            else if (messageUser.Characters.Count == 3 &&
                     (messageUser.Characters[0].Level > 0 ||
                      messageUser.Characters[1].Level > 0 ||
                      messageUser.Characters[2].Level > 0))
            {
                //进入角色选择界面
                SelectCharacterFactory.Create(messageUser);
            }

            Game.EventSystem.Run(EventIdType.SekiaLoginFinish);
        }
Esempio n. 16
0
        public async ETTask StartAsync()
        {
            // 获取远程的Version.txt
            string versionUrl = "";

            try
            {
                using (UnityWebRequestAsync webRequestAsync = ComponentFactory.Create <UnityWebRequestAsync>())
                {
                    versionUrl = GlobalConfigComponent.Instance.GlobalProto.GetUrl() + "StreamingAssets/" + "Version.txt";
                    //Log.Debug(versionUrl);
                    await webRequestAsync.DownloadAsync(versionUrl);

                    remoteVersionConfig = JsonHelper.FromJson <VersionConfig>(webRequestAsync.Request.downloadHandler.text);
                    //Log.Debug(JsonHelper.ToJson(this.VersionConfig));
                }
            }
            catch (Exception e)
            {
                throw new Exception($"url: {versionUrl}", e);
            }

            // 获取streaming目录的Version.txt
            VersionConfig streamingVersionConfig;
            string        versionPath = Path.Combine(PathHelper.AppResPath4Web, "Version.txt");

            using (UnityWebRequestAsync request = ComponentFactory.Create <UnityWebRequestAsync>())
            {
                await request.DownloadAsync(versionPath);

                streamingVersionConfig = JsonHelper.FromJson <VersionConfig>(request.Request.downloadHandler.text);
            }

            // 删掉远程不存在的文件
            DirectoryInfo directoryInfo = new DirectoryInfo(PathHelper.AppHotfixResPath);

            if (directoryInfo.Exists)
            {
                FileInfo[] fileInfos = directoryInfo.GetFiles();
                foreach (FileInfo fileInfo in fileInfos)
                {
                    if (remoteVersionConfig.FileInfoDict.ContainsKey(fileInfo.Name))
                    {
                        continue;
                    }

                    if (fileInfo.Name == "Version.txt")
                    {
                        continue;
                    }

                    fileInfo.Delete();
                }
            }
            else
            {
                directoryInfo.Create();
            }

            // 对比MD5
            foreach (FileVersionInfo fileVersionInfo in remoteVersionConfig.FileInfoDict.Values)
            {
                // 对比md5
                string localFileMD5 = BundleHelper.GetBundleMD5(streamingVersionConfig, fileVersionInfo.File);
                if (fileVersionInfo.MD5 == localFileMD5)
                {
                    continue;
                }
                this.bundles.Enqueue(fileVersionInfo.File);
                this.TotalSize += fileVersionInfo.Size;
            }
        }
Esempio n. 17
0
        /// <summary>
        /// 拿到远程和本地不需要热更的bundle,添加到bundles
        /// </summary>
        /// <returns></returns>
        public async ETTask StartAsync()
        {
            // 获取远程的Version.txt
            string versionUrl = "";

            try
            {
                using (UnityWebRequestAsync webRequestAsync = ComponentFactory.Create <UnityWebRequestAsync>())
                {
                    //web资源服务器地址 本地为http://127.0.0.1:8080/PC/    (PC为平台)
                    versionUrl = GlobalConfigComponent.Instance.GlobalProto.GetUrl() + "StreamingAssets/" + "Version.txt";
                    Log.Debug("web资源服务器地址" + versionUrl);
                    //开始下载版本信息
                    await webRequestAsync.DownloadAsync(versionUrl);

                    //将下载到的远程版本配置信息反序列化为VersionConfig
                    remoteVersionConfig = JsonHelper.FromJson <VersionConfig>(webRequestAsync.Request.downloadHandler.text);
                    Log.Debug("热更新到的VersionConfig:" + JsonHelper.ToJson(this.remoteVersionConfig));
                }
            }
            catch (Exception e)
            {
                throw new Exception($"url: {versionUrl}", e);
            }

            // 获取客户端的Version.txt
            // 获取streaming目录的Version.txt
            VersionConfig streamingVersionConfig;
            //地址合并  拿到本地版本信息文件路径
            string versionPath = Path.Combine(PathHelper.AppResPath4Web, "Version.txt");

            Log.Debug("本地Version.txt地址:" + versionPath);

            using (UnityWebRequestAsync request = ComponentFactory.Create <UnityWebRequestAsync>())
            {
                await request.DownloadAsync(versionPath);

                streamingVersionConfig = JsonHelper.FromJson <VersionConfig>(request.Request.downloadHandler.text);
                Log.Debug("本地Version.txt内容:" + streamingVersionConfig);
            }


            // 删掉远程不存在的文件
            DirectoryInfo directoryInfo = new DirectoryInfo(PathHelper.AppHotfixResPath);

            Log.Debug("应用程序外部资源路径存放路径(热更新资源路径):" + PathHelper.AppHotfixResPath);
            if (directoryInfo.Exists)
            {
                //有此AppHotfixResPath我呢见驾就获取其中文件
                FileInfo[] fileInfos = directoryInfo.GetFiles();

                foreach (FileInfo fileInfo in fileInfos)
                {
                    //远程版本文件中如果有此文件直接跳过
                    if (remoteVersionConfig.FileInfoDict.ContainsKey(fileInfo.Name))
                    {
                        continue;
                    }
                    //是远程版本文件也跳过
                    if (fileInfo.Name == "Version.txt")
                    {
                        continue;
                    }
                    //删除远程版本文件中不存在的资源
                    fileInfo.Delete();
                }
            }
            else
            {
                //热更新资源路径不存在则创建此路径
                directoryInfo.Create();
            }

            // 对比MD5
            foreach (FileVersionInfo fileVersionInfo in remoteVersionConfig.FileInfoDict.Values)
            {
                // 对比md5      (远程文件对应的本地文件的MD5)
                string localFileMD5 = BundleHelper.GetBundleMD5(streamingVersionConfig, fileVersionInfo.File);
                if (fileVersionInfo.MD5 == localFileMD5)
                {
                    continue;
                }
                //添加到bundles队列
                this.bundles.Enqueue(fileVersionInfo.File);
                //总计大小
                this.TotalSize += fileVersionInfo.Size;
            }
        }
        public async Task StartAsync()
        {
            // 获取远程的Version.txt
            string versionUrl = "";

            try
            {
                using (UnityWebRequestAsync webRequestAsync = ComponentFactory.Create <UnityWebRequestAsync>())
                {
                    versionUrl = GlobalConfigComponent.Instance.GlobalProto.GetUrl() + "StreamingAssets/Version.txt";
                    Log.Error("server version=" + versionUrl);
                    await webRequestAsync.DownloadAsync(versionUrl);

                    remoteVersionConfig = JsonHelper.FromJson <VersionConfig>(webRequestAsync.Request.downloadHandler.text);
                    Log.Warning("server version json=" + JsonHelper.ToJson(remoteVersionConfig));
                }
            }
            catch (Exception e)
            {
                throw new Exception($"url: {versionUrl}", e);
            }
            // 获取HotfixResPath目录的Version.txt
            string versionPath = Path.Combine($"file://{PathHelper.AppHotfixResPath}", "Version.txt");

            Log.Debug("local version=" + versionPath);

            using (UnityWebRequestAsync request = ComponentFactory.Create <UnityWebRequestAsync>())//未下载的
            {
                try
                {
                    await request.DownloadAsync(versionPath);

                    streamingVersionConfig = JsonHelper.FromJson <VersionConfig>(request.Request.downloadHandler.text);
                }
                catch (Exception e)
                {
                    Log.Debug($"获取本地目录的Version.txt 失败! Message: {e.Message}");
                }
            }

            // 获取streaming目录的Version.txt
            if (null == streamingVersionConfig)
            {
                // string versionPath = Path.Combine(PathHelper.AppResPath4Web, "Version.txt");
                versionPath = Path.Combine($"file://{PathHelper.AppResPath}", "Version.txt");
                using (UnityWebRequestAsync request = ComponentFactory.Create <UnityWebRequestAsync>())
                {
                    try
                    {
                        await request.DownloadAsync(versionPath);

                        streamingVersionConfig = JsonHelper.FromJson <VersionConfig>(request.Request.downloadHandler.text);
                    }
                    catch (Exception e)
                    {
                        Log.Debug($"获取本地目录的Version.txt 失败! Message: {e.Message}");
                        streamingVersionConfig = new VersionConfig();
                    }
                }
                var verLocal = Path.Combine(PathHelper.AppHotfixResPath, "Version.txt");//创建路径
                if (Directory.Exists(PathHelper.AppHotfixResPath) == false)
                {
                    Directory.CreateDirectory(PathHelper.AppHotfixResPath);
                }
                using (FileStream fs = new FileStream(verLocal, FileMode.Create))//创建
                {
                    VersionConfig t = new VersionConfig()
                    {
                        Version = remoteVersionConfig.Version, TotalSize = 0, ABSecurity = remoteVersionConfig.ABSecurity, FileInfoDict = new Dictionary <string, FileVersionInfo>()
                    };
                    var    json  = JsonHelper.ToJson(t);
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(json);
                    fs.Write(bytes, 0, bytes.Length);
                }
            }

            // 删掉远程不存在的文件
            DirectoryInfo directoryInfo = new DirectoryInfo(PathHelper.AppHotfixResPath);

            if (directoryInfo.Exists)
            {
                FileInfo[] fileInfos = directoryInfo.GetFiles();
                foreach (FileInfo fileInfo in fileInfos)
                {
                    if (remoteVersionConfig.FileInfoDict.ContainsKey(fileInfo.Name))
                    {
                        continue;
                    }
                    if (fileInfo.Name == "Version.txt")
                    {
                        continue;
                    }
                    fileInfo.Delete();
                }
            }
            else
            {
                directoryInfo.Create();
            }

            // 对比MD5
            foreach (FileVersionInfo fileVersionInfo in remoteVersionConfig.FileInfoDict.Values)
            {
                // 对比md5
                string localFileMD5 = BundleHelper.GetBundleMD5(streamingVersionConfig, fileVersionInfo.File);
                if (fileVersionInfo.MD5 == localFileMD5 || fileVersionInfo.File == "Version.txt")//txt不去对比md5
                {
                    continue;
                }
                bundles.Enqueue(fileVersionInfo.File);
                TotalSize += fileVersionInfo.Size;
            }
        }
Esempio n. 19
0
        /// <summary>
        /// 开始下载远程Version文件进行本地对比 确认需要下载的AB包文件
        /// </summary>
        /// <returns></returns>
        public async Task StartAsync()
        {
            // 获取远程的Version.txt
            string versionUrl = "";

            try
            {
                using (UnityWebRequestAsync webRequestAsync = ComponentFactory.Create <UnityWebRequestAsync>())
                {
                    //从Resources文件夹读取“VK”预制体上的TXT文档取得AB资源服务区地址 得到最新的Version.txt
                    versionUrl = GlobalConfigComponent.Instance.GlobalProto.GetUrl() + "StreamingAssets/" + "Version.txt";
                    //Log.Debug(versionUrl);
                    await webRequestAsync.DownloadAsync(versionUrl);                     //下载资源

                    remoteVersionConfig = JsonHelper.FromJson <VersionConfig>(webRequestAsync.Request.downloadHandler.text);
                    //Log.Debug(JsonHelper.ToJson(this.VersionConfig));
                }
            }
            catch (Exception e)
            {
                throw new Exception($"url: {versionUrl}", e);
            }

            // 获取streaming目录的Version.txt
            VersionConfig streamingVersionConfig;
            //得到本地Version文件地址
            string versionPath = Path.Combine(PathHelper.AppResPath4Web, "Version.txt");

            using (UnityWebRequestAsync request = ComponentFactory.Create <UnityWebRequestAsync>())
            {
                await request.DownloadAsync(versionPath);

                streamingVersionConfig = JsonHelper.FromJson <VersionConfig>(request.Request.downloadHandler.text);
            }

            // 删掉远程不存在的文件 获取本地热更新文件夹
            DirectoryInfo directoryInfo = new DirectoryInfo(PathHelper.AppHotfixResPath);

            if (directoryInfo.Exists)             //如果有这个文件夹
            {
                //得到文件夹内所有文件
                FileInfo[] fileInfos = directoryInfo.GetFiles();
                foreach (FileInfo fileInfo in fileInfos)
                {
                    //新的版本配置表中没有这个文件 就删除此文件
                    if (remoteVersionConfig.FileInfoDict.ContainsKey(fileInfo.Name))
                    {
                        continue;
                    }

                    if (fileInfo.Name == "Version.txt")
                    {
                        continue;
                    }

                    fileInfo.Delete();
                }
            }
            else
            {
                //否则就创建新的热更新资源文件夹
                directoryInfo.Create();
            }

            // 对比MD5
            foreach (FileVersionInfo fileVersionInfo in remoteVersionConfig.FileInfoDict.Values)
            {
                // 本地
                string localFileMD5 = BundleHelper.GetBundleMD5(streamingVersionConfig, fileVersionInfo.File);
                if (fileVersionInfo.MD5 == localFileMD5)
                {
                    continue;
                }
                this.bundles.Enqueue(fileVersionInfo.File);                 //需要重新下载的AB包的名字
                this.TotalSize += fileVersionInfo.Size;                     //需要下载的资源的总大小
            }
        }
Esempio n. 20
0
        public void Run(int horseId, int skillId, bool isRemove)
        {
            //GameRunMatchComponent gameRunMatchComponent = Game.Scene.GetComponent<GameRunMatchComponent>();
            //if (gameRunMatchComponent == null || gameRunMatchComponent.IsDisposed)
            //    return;

            MatchModule    matchModule   = UtilsModuleManager.GetModule(ModuleType.MatchModule) as MatchModule;
            ModelHorseView findHorseView = matchModule.ModelHorseViewSet.Find(x => x.data.Id == horseId);

            //HorseView findHorseView = gameRunMatchComponent.GetHorseView(horseId);
            if (findHorseView == null)
            {
                Log.Error("没有这个马匹:" + horseId);
                return;
            }
            HorseSkillDefine horseSkillDefine = ModelComTools.Config.GetHorseSkillByID(skillId);

            if (horseSkillDefine == null)
            {
                Log.Error("没有这个技能:" + skillId);
                return;
            }
            List <int> skills = new List <int> {
                50080040, 50080041, 50080042, 50080043, 50080044, 50080045, 50080046, 50080047, 50080048, 50080049, 50080050, 50080051, 50080052, 50080053, 50080054, 50080055, 50080056, 50080057, 50080058, 50080059, 50080060, 50080061, 50080062, 50080063, 50080064, 50080065, 50080066, 50080067, 50080068, 50080069, 50080070
            };

            if (skills.Contains(horseSkillDefine.Name))
            {
                return;
            }
            string skillName = GameObjectTool.GetLanguage(horseSkillDefine.Name);
            string skillDesc = GameObjectTool.GetLanguage(horseSkillDefine.Describe);
            UIBattleMainComponent uiComponent = matchModule.uIBattleMainComponent;

            if (uiComponent != null)
            {
                var    tips      = GameObjectTool.GetLanguage(50138126);        //触发
                var    tips1     = GameObjectTool.GetLanguage(50138127);        //结束
                string skillInfo = string.Format(tips, horseId + 1, skillName); // $"<color=#24f50a>{horseId + 1}号赛马</color>:触发{skillName}技能";//,{skillDesc}";
                if (isRemove)
                {
                    skillInfo = string.Format(tips1, horseId + 1, skillName);//$"<color=#24f50a>{horseId + 1}号赛马</color>:技能{skillName}结束";
                }
                else
                {
                    if (horseSkillDefine.ExistTime > 0)
                    {
                        TimeCountDownComponent TimeCountDownComponentSkill = ComponentFactory.Create <TimeCountDownComponent>();
                        TimeCountDownComponentSkill.Init(horseSkillDefine.ExistTime, null, string.Empty, () =>
                        {
                            skillInfo = string.Format(tips1, horseId + 1, skillName);//$"<color=#24f50a>{horseId + 1}号赛马</color>:技能{skillName}结束";
                            uiComponent.AddSkillInfo(skillInfo);
                            TimeCountDownComponentSkill.Dispose();
                        });
                    }
                }
                uiComponent.AddSkillInfo(skillInfo);

                if (findHorseView.data.playerUid == matchModule.playerUID)
                {
                    uiComponent.SetSelfSkill(skillName, isRemove, skillId, horseSkillDefine.ExistTime);
                }
            }
        }
Esempio n. 21
0
        //对比本地资源和服务器资源
        public async ETTask StartAsync(string fileFoldr = "", string versionName = "Version.txt")
        {
            downloadFoldr = fileFoldr;
            // 获取远程的Version.txt
            string versionUrl = "";

            try
            {
                using (UnityWebRequestAsync webRequestAsync = ComponentFactory.Create <UnityWebRequestAsync>())
                {
                    versionUrl = Path.Combine(GlobalConfigComponent.Instance.GlobalProto.GetUrl(), "StreamingAssets", downloadFoldr, versionName);
                    await webRequestAsync.DownloadAsync(versionUrl);

                    remoteVersionConfig = JsonHelper.FromJson <VersionConfig>(webRequestAsync.Request.downloadHandler.text);
                }
            }
            catch (Exception e)
            {
                pLoserCall?.Invoke(e.ToString());
                throw new Exception($"url: {versionUrl}", e);
            }

            // 删掉远程不存在的文件
            DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(PathHelper.AppHotfixResPath, downloadFoldr));

            if (directoryInfo.Exists)
            {
                FileInfo[] fileInfos = directoryInfo.GetFiles();
                foreach (FileInfo fileInfo in fileInfos)
                {
                    if (remoteVersionConfig.FileInfoDict.ContainsKey(fileInfo.Name))
                    {
                        continue;
                    }
                    if (fileInfo.Name == versionName)
                    {
                        continue;
                    }
                    fileInfo.Delete();
                }
            }
            else
            {
                directoryInfo.Create();
            }


            // 对比MD5
            foreach (FileVersionInfo fileVersionInfo in remoteVersionConfig.FileInfoDict.Values)
            {
                // 对比md5
                string localFileMD5 = BundleHelper.GetBundleMD5(fileVersionInfo.File);
                if (fileVersionInfo.MD5 == localFileMD5)
                {
                    continue;
                }
                this.bundles.Enqueue(fileVersionInfo.File);
                this.TotalSize += fileVersionInfo.Size;
            }
            await DownloadAsync();
        }
Esempio n. 22
0
        public void OnAccept(AChannel channel)
        {
            Session session = ComponentFactory.CreateWithParent <Session, AChannel>(this, channel);

            this.sessions.Add(session.Id, session);
        }
Esempio n. 23
0
        //A0 01注册 02登录realm 03登录gate
        public static async ETVoid Login(string account, string password)
        {
            LandLoginComponent login = Game.Scene.GetComponent <UIComponent>().Get(LandUIType.LandLogin).GetComponent <LandLoginComponent>();

            //创建Realm session
            Session         sessionRealm = Game.Scene.GetComponent <NetOuterComponent>().Create(GlobalConfigComponent.Instance.GlobalProto.Address);
            A0002_Login_R2C messageRealm = (A0002_Login_R2C)await sessionRealm.Call(new A0002_Login_C2R()
            {
                Account = account, Password = password
            });

            sessionRealm.Dispose();
            login.prompt.text = "正在登录中...";

            //判断Realm服务器返回结果
            if (messageRealm.Error == ErrorCode.ERR_AccountOrPasswordError)
            {
                login.prompt.text   = "登录失败,账号或密码错误";
                login.account.text  = "";
                login.password.text = "";
                login.isLogining    = false;
                return;
            }
            //判断通过则登陆Realm成功

            //创建网关 session
            Session sessionGate = Game.Scene.GetComponent <NetOuterComponent>().Create(messageRealm.GateAddress);

            if (SessionComponent.Instance == null)
            {
                Log.Debug("创建唯一Session");
                Game.Scene.AddComponent <SessionComponent>().Session = sessionGate;
            }
            else
            {
                //存入SessionComponent方便我们随时使用
                Log.Debug("存入SessionComponent方便我们随时使用");
                SessionComponent.Instance.Session = sessionGate;
                //Game.EventSystem.Run(EventIdType.SetHotfixSession);
            }

            A0003_LoginGate_G2C messageGate = (A0003_LoginGate_G2C)await sessionGate.Call(new A0003_LoginGate_C2G()
            {
                GateLoginKey = messageRealm.GateLoginKey
            });

            //判断登陆Gate服务器返回结果
            if (messageGate.Error == ErrorCode.ERR_ConnectGateKeyError)
            {
                login.prompt.text   = "连接网关服务器超时";
                login.account.text  = "";
                login.password.text = "";
                sessionGate.Dispose();
                login.isLogining = false;
                return;
            }
            //判断通过则登陆Gate成功

            login.prompt.text = "";
            User user = ComponentFactory.Create <User, long>(messageGate.UserID);

            GamerComponent.Instance.MyUser = user;
            //Log.Debug("登陆成功");

            //加载透明界面 退出当前界面
            Game.EventSystem.Run(UIEventType.LandLoginFinish);

            // 加载大厅界面
            Game.EventSystem.Run(UIEventType.LandInitLobby);
        }
Esempio n. 24
0
        /// <summary>
        /// 创建一个行为树实例,默认存入Unit的NP_RuntimeTreeManager中
        /// </summary>
        /// <param name="unit">行为树所归属unit</param>
        /// <param name="nPDataId">行为树数据id</param>
        /// <returns></returns>
        public static NP_RuntimeTree CreateNpRuntimeTree(Unit unit, long nPDataId)
        {
            NP_DataSupportor npDataSupportor =
                Game.Scene.GetComponent <NP_TreeDataRepository>().GetNP_TreeData_DeepCopyBBValuesOnly(nPDataId);

            NP_RuntimeTree tempTree =
                ComponentFactory.Create <NP_RuntimeTree, NP_DataSupportor, long>(npDataSupportor, unit.Id);

            long rootId = npDataSupportor.NpDataSupportorBase.NPBehaveTreeDataId;

            unit.GetComponent <NP_RuntimeTreeManager>().AddTree(tempTree.Id, rootId, tempTree);

            //Log.Info($"运行时id为{theRuntimeTreeID}");
            //配置节点数据
            foreach (var nodeDateBase in npDataSupportor.NpDataSupportorBase.NP_DataSupportorDic)
            {
                switch (nodeDateBase.Value.NodeType)
                {
                case NodeType.Task:
                    try
                    {
                        nodeDateBase.Value.CreateTask(unit.Id, tempTree);
                    }
                    catch (Exception e)
                    {
                        Log.Error($"{e}-----{nodeDateBase.Value.NodeDes}");
                        throw;
                    }

                    break;

                case NodeType.Decorator:
                    try
                    {
                        nodeDateBase.Value.CreateDecoratorNode(unit.Id, tempTree,
                                                               npDataSupportor.NpDataSupportorBase.NP_DataSupportorDic[nodeDateBase.Value.LinkedIds[0]].NP_GetNode());
                    }
                    catch (Exception e)
                    {
                        Log.Error($"{e}-----{nodeDateBase.Value.NodeDes}");
                        throw;
                    }

                    break;

                case NodeType.Composite:
                    try
                    {
                        List <Node> temp = new List <Node>();
                        foreach (var linkedId in nodeDateBase.Value.LinkedIds)
                        {
                            temp.Add(npDataSupportor.NpDataSupportorBase.NP_DataSupportorDic[linkedId].NP_GetNode());
                        }

                        nodeDateBase.Value.CreateComposite(temp.ToArray());
                    }
                    catch (Exception e)
                    {
                        Log.Error($"{e}-----{nodeDateBase.Value.NodeDes}");
                        throw;
                    }

                    break;
                }
            }

            //配置根结点
            tempTree.SetRootNode(npDataSupportor.NpDataSupportorBase.NP_DataSupportorDic[rootId].NP_GetNode() as Root);

            //配置黑板数据
            Dictionary <string, ANP_BBValue> bbvaluesManager = tempTree.GetBlackboard().GetDatas();

            foreach (var bbValues in npDataSupportor.NpDataSupportorBase.NP_BBValueManager)
            {
                bbvaluesManager.Add(bbValues.Key, bbValues.Value);
            }

            return(tempTree);
        }
Esempio n. 25
0
 public override void Awake(FUIComponent self)
 {
     GRoot.inst.SetContentScaleFactor(1280, 720, UIContentScaler.ScreenMatchMode.MatchWidthOrHeight);
     self.Root = ComponentFactory.Create <FUI, GObject>(GRoot.inst);
 }
Esempio n. 26
0
        public async ETTask StartAsync()
        {
            alreadyDownloadBytes = 0;

            TotalSize = 0;

            CurrVersionBytes = 0;

            string versionUrl = "";

            versionUrl = GlobalConfigComponent.Instance.GlobalProto.GetUrl() + "StreamingAssets/" + "Version.txt";

            Log.Debug($"当前资源为AB模式,远程版本文件路径:" + versionUrl);

            try
            {
                using (UnityWebRequestAsync webRequestAsync = ComponentFactory.Create <UnityWebRequestAsync>())
                {
                    await webRequestAsync.DownloadAsync(versionUrl);

                    CurrVersionBytes += (long)webRequestAsync.Request.downloadedBytes;

                    // 获取远程的Version.txt
                    remoteVersionConfig = JsonHelper.FromJson <VersionConfig>(webRequestAsync.Request.downloadHandler.text);
                }
            }
            catch (Exception e)
            {
                Log.Error($"download version.txt error: {e}");
                return;
            }

            // 获取streaming目录的Version.txt
            VersionConfig streamingVersionConfig;

            string versionPath = Path.Combine(PathHelper.AppResPath4Web, "Version.txt");

            using (UnityWebRequestAsync request = ComponentFactory.Create <UnityWebRequestAsync>())
            {
                Log.Debug("本地版本文件路径:" + versionPath);

                await request.DownloadAsync(versionPath);

                streamingVersionConfig = JsonHelper.FromJson <VersionConfig>(request.Request.downloadHandler.text);
            }

            // 删掉远程不存在的文件
            DirectoryInfo directoryInfo = new DirectoryInfo(PathHelper.AppHotfixResPath);

            if (directoryInfo.Exists)
            {
                FileInfo[] fileInfos = directoryInfo.GetFiles();
                foreach (FileInfo fileInfo in fileInfos)
                {
                    if (remoteVersionConfig.FileInfoDict.ContainsKey(fileInfo.Name))
                    {
                        continue;
                    }

                    if (fileInfo.Name == "Version.txt")
                    {
                        continue;
                    }

                    fileInfo.Delete();
                }
            }
            else
            {
                directoryInfo.Create();
            }
            // 对比MD5
            foreach (FileVersionInfo fileVersionInfo in remoteVersionConfig.FileInfoDict.Values)
            {
                // 对比md5
                string localFileMD5 = BundleHelper.GetBundleMD5(streamingVersionConfig, fileVersionInfo.File);
                //如果MD5相同,且当前项目不含有这个文件
                if (fileVersionInfo.MD5 == localFileMD5)
                {
                    continue;
                }

                if (IsFilterRes(fileVersionInfo.File))
                {
                    continue;
                }

                this.bundles.Enqueue(fileVersionInfo.File);

                this.TotalSize += fileVersionInfo.Size;
            }
        }
Esempio n. 27
0
        /// <summary>
        /// 异步加载AB包
        /// </summary>
        /// <returns></returns>
        private async ETTask DownloadAsync()
        {
            if (this.bundles.Count == 0 && this.downloadingBundle == "")
            {
                return;
            }

            try
            {
                while (true)
                {
                    if (this.bundles.Count == 0)
                    {
                        break;
                    }
                    this.downloadingBundle = this.bundles.Dequeue();

                    while (true)
                    {
                        try
                        {
                            using (this.webRequest = ComponentFactory.Create <UnityWebRequestAsync>())
                            {
                                await this.webRequest.DownloadAsync(GlobalConfigComponent.Instance.GlobalProto.GetUrl() + "StreamingAssets/" + this.downloadingBundle);

                                byte[] data = this.webRequest.Request.downloadHandler.data;

                                this.alreadyDownloadBytes += (long)this.webRequest.Request.downloadedBytes;

                                string path = Path.Combine(PathHelper.AppHotfixResPath, this.downloadingBundle);

                                using (FileStream fs = new FileStream(path, FileMode.Create))
                                {
                                    fs.Write(data, 0, data.Length);
                                }

                                Log.Debug($"current downloadingBundle ------->>>{this.downloadingBundle}");
                            }
                        }
                        catch (Exception e)
                        {
                            // Log.Debug($"download bundle error:{this.downloadingBundle}\n{e}");

                            continue;
                        }

                        break;
                    }
                }

                this.downloadedBundles.Add(this.downloadingBundle);

                this.downloadingBundle = "";

                this.webRequest = null;
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
Esempio n. 28
0
        public async Task StartAsync()
        {
            using (UnityWebRequestAsync request = ComponentFactory.Create <UnityWebRequestAsync>())
            {
                string versionUrl = GlobalConfigComponent.Instance.GlobalProto.GetUrl() + "StreamingAssets/" + "Version.txt";
                Log.Debug(versionUrl);
                await request.DownloadAsync(versionUrl);

                this.VersionConfig = JsonHelper.FromJson <VersionConfig>(request.Request.downloadHandler.text);
            }

            Log.Debug("WebVersion:\n" + JsonHelper.ToJson(this.VersionConfig));

            // 对比本地的Version.txt
            string versionPath = Path.Combine(PathHelper.AppHotfixResPath, "Version.txt");

            if (!File.Exists(versionPath))
            {
                foreach (FileVersionInfo versionInfo in this.VersionConfig.FileInfoDict.Values)
                {
                    if (versionInfo.File == "Version.txt")
                    {
                        continue;
                    }
                    this.bundles.Enqueue(versionInfo.File);
                    this.TotalSize += versionInfo.Size;
                }
            }
            else
            {
                VersionConfig localVersionConfig = JsonHelper.FromJson <VersionConfig>(File.ReadAllText(versionPath));
                Log.Debug("LocalVersion:\n" + JsonHelper.ToJson(localVersionConfig));
                // 先删除服务器端没有的ab
                foreach (FileVersionInfo fileVersionInfo in localVersionConfig.FileInfoDict.Values)
                {
                    if (this.VersionConfig.FileInfoDict.ContainsKey(fileVersionInfo.File))
                    {
                        continue;
                    }
                    string abPath = Path.Combine(PathHelper.AppHotfixResPath, fileVersionInfo.File);
                    File.Delete(abPath);
                }

                // 再下载
                foreach (FileVersionInfo fileVersionInfo in this.VersionConfig.FileInfoDict.Values)
                {
                    FileVersionInfo localVersionInfo;
                    if (localVersionConfig.FileInfoDict.TryGetValue(fileVersionInfo.File, out localVersionInfo))
                    {
                        if (fileVersionInfo.MD5 == localVersionInfo.MD5)
                        {
                            continue;
                        }
                    }

                    if (fileVersionInfo.File == "Version.txt")
                    {
                        continue;
                    }

                    this.bundles.Enqueue(fileVersionInfo.File);
                    this.TotalSize += fileVersionInfo.Size;
                }
            }

            if (this.bundles.Count == 0)
            {
                return;
            }

            Log.Debug($"need download bundles: {this.bundles.ToList().ListToString()}");
            await this.WaitAsync();
        }
Esempio n. 29
0
        public async Task LoadOneBundleAsync(string assetBundleName)
        {
            ABInfo abInfo;

            if (this.bundles.TryGetValue(assetBundleName, out abInfo))
            {
                ++abInfo.RefCount;
                return;
            }

            //Log.Debug($"---------------load one bundle {assetBundleName}");
            if (!Define.IsAsync)
            {
                string[] realPath = null;
#if UNITY_EDITOR
                realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
                foreach (string s in realPath)
                {
                    string             assetName = Path.GetFileNameWithoutExtension(s);
                    UnityEngine.Object resource  = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(s);
                    AddResource(assetBundleName, assetName, resource);
                }

                this.bundles[assetBundleName] = new ABInfo(assetBundleName, null);
#endif
                return;
            }

            string      p           = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
            AssetBundle assetBundle = null;
            if (!File.Exists(p))
            {
                p = Path.Combine(PathHelper.AppResPath, assetBundleName);
            }

            using (AssetsBundleLoaderAsync assetsBundleLoaderAsync = ComponentFactory.Create <AssetsBundleLoaderAsync>())
            {
                assetBundle = await assetsBundleLoaderAsync.LoadAsync(p);
            }

            if (assetBundle == null)
            {
                throw new Exception($"assets bundle not found: {assetBundleName}");
            }

            if (!assetBundle.isStreamedSceneAssetBundle)
            {
                // 异步load资源到内存cache住
                UnityEngine.Object[] assets;
                using (AssetsLoaderAsync assetsLoaderAsync = ComponentFactory.Create <AssetsLoaderAsync, AssetBundle>(assetBundle))
                {
                    assets = await assetsLoaderAsync.LoadAllAssetsAsync();
                }
                foreach (UnityEngine.Object asset in assets)
                {
                    AddResource(assetBundleName, asset.name, asset);
                }
            }

            this.bundles[assetBundleName] = new ABInfo(assetBundleName, assetBundle);
        }
Esempio n. 30
0
        public static Unit Create(long id, int typeId, UnitData unitData)
        {
            ResourcesComponent resourcesComponent = Game.Scene.GetComponent <ResourcesComponent>();

            UnitConfig unitConfig = Game.Scene.GetComponent <ConfigComponent>().Get(typeof(UnitConfig), typeId) as UnitConfig;

            resourcesComponent.LoadBundle(unitConfig.ABPacketName.ToLower().StringToAB());

            GameObject    bundleGameObject = (GameObject)resourcesComponent.GetAsset(unitConfig.ABPacketName.ToLower().StringToAB(), unitConfig.ABPacketName);
            UnitComponent unitComponent    = Game.Scene.GetComponent <UnitComponent>();

            GameObject go   = UnityEngine.Object.Instantiate(bundleGameObject);
            Unit       unit = ComponentFactory.CreateWithId <Unit, GameObject>(id, go);

            unit.AddComponent <NumericComponent, int>(typeId);
            unit.AddComponent <AnimatorComponent>();
            unit.AddComponent <UnitStateComponent>();
            unit.AddComponent <UnitPathComponent>();
            unit.AddComponent <AudioComponent>();
            unit.AddComponent <BuffMgrComponent>();
            var activeSkillCom  = unit.AddComponent <ActiveSkillComponent>();
            var passiveSkillCom = unit.AddComponent <PassiveSkillComponent>();

            unit.AddComponent <SkillEffectComponent>();
            if (!GlobalConfigComponent.Instance.networkPlayMode)
            {
                //添加碰撞体
                AddCollider(unit, unitData, true);
            }
            unit.AddComponent <CharacterStateComponent>();
            unit.AddComponent <CharacterMoveComponent>();

            if (!Game.Scene.GetComponent <GlobalConfigComponent>().networkPlayMode)
            {
                unit.AddComponent <CalNumericComponent>();
            }


            if (unitConfig.Skills != null && unitConfig.Skills.Length > 0)
            {
                SkillConfigComponent skillConfigComponent = Game.Scene.GetComponent <SkillConfigComponent>();
                foreach (var v in unitConfig.Skills)
                {
                    if (string.IsNullOrEmpty(v))
                    {
                        continue;
                    }
                    var activeSkill = skillConfigComponent.GetActiveSkill(v);
                    if (activeSkill != null)
                    {
                        Log.Debug(string.Format("{0} 添加主动技能 {1} ({2})成功!", typeId, v, activeSkill.skillName));
                        activeSkillCom.AddSkill(v);
                        continue;
                    }
                    var passiveSkill = skillConfigComponent.GetPassiveSkill(v);
                    if (passiveSkill != null)
                    {
                        Log.Debug(string.Format("{0} 添加被动技能 {1} ({2})成功!", typeId, v, passiveSkill.skillName));
                        passiveSkillCom.AddSkill(v);
                        continue;
                    }
                    Log.Error(v + "  这样的技能不存在!");
                }
            }

            //unit.AddComponent<TurnComponent>();

            unitComponent.Add(unit);
            return(unit);
        }