英雄联盟——总结

BaseWindow    Awake  OnEnble  Start

策划拼UI

减少包体:3D模型材质,模型面数

                   UI资源共用,例如弹出面板做成一样的

                   图片没有透明通道的采用jpg

                   有透明通道的用png

图片压缩方式:android用  ETC 

                        IOS用pv RTC

 public abstract class BaseWindow
    {
        protected Transform mRoot;

        protected EScenesType mScenesType; //场景类型
        protected string mResName;         //资源路径名
        protected bool mResident;          //是否常驻 
        protected bool mVisible = false;   //是否可见
      

        //类对象初始化
        public abstract void Init();

        //类对象释放
        public abstract void Realse();

        //窗口控制初始化
        protected abstract void InitWidget();

        //窗口控件释放
        protected abstract void RealseWidget();

        //游戏事件注册
        protected abstract void OnAddListener();

        //游戏事件注消
        protected abstract void OnRemoveListener();

        //显示初始化
        public abstract void OnEnable();

        //隐藏处理
        public abstract void OnDisable();

        //每帧更新
        public virtual void Update(float deltaTime) { }

        //取得所以场景类型
        public EScenesType GetScenseType()
        {
            return mScenesType;
        }

        //是否已打开
        public bool IsVisible() { return mVisible;  }

        //是否常驻
        public bool IsResident() { return mResident; }

        //显示
        public void Show()
        {
            if (mRoot == null)
            {
                if (Create())
                {
                    InitWidget();
                }
            }

            if (mRoot && mRoot.gameObject.activeSelf == false)
            {
                mRoot.gameObject.SetActive(true);

                mVisible = true;

                OnEnable();

                OnAddListener();
            }
        }

        //隐藏
        public void Hide()
        {
            if (mRoot && mRoot.gameObject.activeSelf == true)
            {
                OnRemoveListener();
                OnDisable();

                if (mResident)
                {
                    mRoot.gameObject.SetActive(false);
                }
                else
                {
                    RealseWidget();
                    Destroy();
                }
            }

            mVisible = false;
        }

        //预加载的时候创建窗体
        public void PreLoad()
        {
            if (mRoot == null)
            {
                if (Create())
                {
                    InitWidget();//面板中的button响应
                }
            }
        }

        //延时删除
        public void DelayDestory()
        {
            if (mRoot)
            {
                RealseWidget();
                Destroy();
            }
        }

        //创建窗体
        private bool Create()
        {
            if (mRoot)
            {
                Debug.LogError("Window Create Error Exist!");
                return false;
            }

            if (mResName == null || mResName == "")
            {
                Debug.LogError("Window Create Error ResName is empty!");
                return false;
            }

            if (GameMethod.GetUiCamera.transform== null)
            {
                Debug.LogError("Window Create Error GetUiCamera is empty! WindowName = " + mResName);
                return false;
            }

            GameObject obj = LoadUiResource.LoadRes(GameMethod.GetUiCamera.transform, mResName);//UI存放的父物体类

            if (obj == null)
            {
                Debug.LogError("Window Create Error LoadRes WindowName = " + mResName);
                return false;
            }

            mRoot = obj.transform;

            mRoot.gameObject.SetActive(false);

            return true;
        }

        //销毁窗体
        protected void Destroy()
        {
            if (mRoot)
            {
                LoadUiResource.DestroyLoad(mRoot.gameObject);
                mRoot = null;
            }
        }

        //取得根节点
        public Transform GetRoot()
        {
            return mRoot;
        }

    }
}

 

 

public class LoadUiResource
{
	public static GameObject LoadRes(Transform parent,string path)
	{
		if(CheckResInDic(path))			
		{
			if(GetResInDic(path) != null){
				return GetResInDic(path);
			}
			else{
				LoadResDic.Remove(path);
			}
		}
		
		GameObject objLoad = null;

        ResourceUnit objUnit = ResourcesManager.Instance.loadImmediate(path, ResourceType.PREFAB);
        if (objUnit == null || objUnit.Asset == null)
        {
            Debug.LogError("load unit failed" + path);
            return null;
        }
        objLoad = GameObject.Instantiate(objUnit.Asset) as GameObject;
		objLoad.transform.parent = parent;
		objLoad.transform.localScale = Vector3.one;
		objLoad.transform.localPosition = Vector3.zero;
		LoadResDic.Add(path,objLoad);
		return objLoad;
	}

    //创建窗口子对象,不加入资源管理
    public static GameObject AddChildObject(Transform parent, string path)
    {
        GameObject objLoad = null;

        ResourceUnit objUnit = ResourcesManager.Instance.loadImmediate(path, ResourceType.PREFAB);
        if (objUnit == null || objUnit.Asset == null)
        {
            Debug.LogError("load unit failed" + path);
            return null;
        }
        objLoad = GameObject.Instantiate(objUnit.Asset) as GameObject;
        objLoad.transform.parent = parent;
        objLoad.transform.localScale = Vector3.one;
        objLoad.transform.localPosition = Vector3.zero;

        return objLoad;
    }

    public static void ClearAllChild(Transform transform)
    {
        while (transform.childCount > 0)
        {
            GameObject.DestroyImmediate(transform.GetChild(0).gameObject);
        }
        transform.DetachChildren();
    }

    public static void ClearOneChild(Transform transform,string name)
    {
        for (int i = 0; i < transform.childCount; i++)
        {
            if (transform.GetChild(i).gameObject.name == name)
            {
                GameObject.DestroyImmediate(transform.GetChild(i).gameObject);
            }
        }
    }

	public static void DestroyLoad(string path)
	{
		if(LoadResDic == null || LoadResDic.Count == 0)
			return;
		GameObject obj = null;
        if (LoadResDic.TryGetValue(path, out obj) && obj != null)
		{
			GameObject.DestroyImmediate(obj);
			LoadResDic.Remove(path);
			//System.GC.Collect();
		}
	}
	
	public static void DestroyLoad(GameObject obj)
	{
		if(LoadResDic == null || LoadResDic.Count == 0)
			return;
		if(obj == null)
			return;
		foreach(string key in LoadResDic.Keys)
		{
			GameObject objLoad;
			if(LoadResDic.TryGetValue(key,out objLoad) && objLoad == obj)
			{
				GameObject.DestroyImmediate(obj);
				LoadResDic.Remove(key);
				break;
			}
		}		
	}


	public static GameObject GetResInDic(string path)
	{
		if(LoadResDic == null || LoadResDic.Count == 0)
			return null;
		GameObject obj = null ;
		if(LoadResDic.TryGetValue(path,out obj))
		{
			return obj;
		}
		return null;
	}
	
	public  static bool CheckResInDic(string path)
	{
		if(LoadResDic == null || LoadResDic.Count == 0)
			return false;
		return LoadResDic.ContainsKey(path);
	}
	
	public static void Clean()
	{
		if(LoadResDic == null || LoadResDic.Count == 0)
			return;
		for(int i = LoadResDic.Count - 1;i >=0;i--)
		{
			GameObject obj = LoadResDic.ElementAt(i).Value ;
			if( obj != null)
			{
				GameObject.DestroyImmediate(obj);
			}
		}
		LoadResDic.Clear();
	}

	public static Dictionary<string,GameObject> LoadResDic = new Dictionary<string, GameObject>();

}

WindowManager基类中缓存所有的UI脚本

namespace Game.View
{
    public enum EScenesType
    {
        EST_None,
        EST_Login,
        EST_Play,
    }

    public enum EWindowType
    {
        EWT_LoginWindow, //登录
        EWT_UserWindow, //用户界面
        EWT_LobbyWindow,
        EWT_BattleWindow,
        EWT_RoomWindow,
        EWT_HeroWindow,
        EWT_BattleInfoWindow,
        EWT_MarketWindow,
        EWT_MarketHeroListWindow,
        EWT_MarketHeroInfoWindow,
        EWT_MarketRuneListWindow,
        EWT_MarketRuneInfoWindow,
        EWT_SocialWindow,
        EWT_GamePlayWindow,
        EWT_InviteWindow,
        EWT_ChatTaskWindow,
        EWT_ScoreWindow,
        EWT_InviteAddRoomWindow,
        EWT_RoomInviteWindow,
        EWT_TeamMatchWindow,
        EWT_TeamMatchInvitationWindow,
        EWT_TeamMatchSearchingWindow,
        EWT_MailWindow,
        EWT_HomePageWindow,
        EWT_PresonInfoWindow,
        EWT_ServerMatchInvitationWindow,
        EWT_SoleSoldierWindow,
        EWT_MessageWindow,
        EWT_MiniMapWindow,
        EWT_VIPPrerogativeWindow,
        EWT_RuneEquipWindow,
        EWT_DaliyBonusWindow,
        EWT_EquipmentWindow,
        EWT_SystemNoticeWindow,
        EWT_TimeDownWindow,
        EWT_RuneCombineWindow,
		EWT_HeroDatumWindow,
		EWT_RuneRefreshWindow,
        EWT_GamePlayGuideWindow,
        EMT_PurchaseSuccessWindow,
        EMT_GameSettingWindow,
        EMT_AdvancedGuideWindow,
        EMT_ExtraBonusWindow,
        EMT_EnemyWindow,
        EMT_HeroTimeLimitWindow,
        EMT_SkillWindow,
        EMT_SkillDescribleWindow,
        EMT_RuneBuyWindow,
        EMT_DeathWindow,
    }

    public class WindowManager : Singleton<WindowManager>
    {
        public WindowManager()
        {
            mWidowDic = new Dictionary<EWindowType, BaseWindow>();

            //注册类
            mWidowDic[EWindowType.EWT_LoginWindow] = new LoginWindow();
            mWidowDic[EWindowType.EWT_UserWindow] = new UserInfoWindow();
            mWidowDic[EWindowType.EWT_LobbyWindow] = new LobbyWindow();
            mWidowDic[EWindowType.EWT_BattleWindow] = new BattleWindow();
            mWidowDic[EWindowType.EWT_RoomWindow] = new RoomWindow();
            mWidowDic[EWindowType.EWT_HeroWindow] = new HeroWindow();
            mWidowDic[EWindowType.EWT_BattleInfoWindow] = new BattleInfoWindow();
            mWidowDic[EWindowType.EWT_MarketWindow] = new MarketWindow();
            mWidowDic[EWindowType.EWT_MarketHeroListWindow] = new MarketHeroListWindow();
            mWidowDic[EWindowType.EWT_MarketHeroInfoWindow] = new MarketHeroInfoWindow();    
            mWidowDic[EWindowType.EWT_SocialWindow] = new SocialWindow();
            mWidowDic[EWindowType.EWT_GamePlayWindow] = new GamePlayWindow();
            mWidowDic[EWindowType.EWT_InviteWindow] = new InviteWindow();
            mWidowDic[EWindowType.EWT_ChatTaskWindow] = new ChatTaskWindow();
            mWidowDic[EWindowType.EWT_ScoreWindow] = new ScoreWindow();
            mWidowDic[EWindowType.EWT_InviteAddRoomWindow] = new InviteAddRoomWindow();
            mWidowDic[EWindowType.EWT_RoomInviteWindow] = new RoomInviteWindow();
            mWidowDic[EWindowType.EWT_TeamMatchWindow] = new TeamMatchWindow();
            mWidowDic[EWindowType.EWT_TeamMatchInvitationWindow] = new TeamMatchInvitationWindow();
            mWidowDic[EWindowType.EWT_TeamMatchSearchingWindow] = new TeamMatchSearchingWindow();
            mWidowDic[EWindowType.EWT_MailWindow] = new MailWindow();
            mWidowDic[EWindowType.EWT_HomePageWindow] = new HomePageWindow(); 
            mWidowDic[EWindowType.EWT_PresonInfoWindow] = new PresonInfoWindow();
            mWidowDic[EWindowType.EWT_ServerMatchInvitationWindow] = new ServerMatchInvitationWindow();
            mWidowDic[EWindowType.EWT_SoleSoldierWindow] = new SoleSoldierWindow();
            mWidowDic[EWindowType.EWT_MessageWindow] = new MessageWindow();
            mWidowDic[EWindowType.EWT_MarketRuneListWindow] = new MarketRuneListWindow();
            mWidowDic[EWindowType.EWT_MiniMapWindow] = new MiniMapWindow();
            mWidowDic[EWindowType.EWT_MarketRuneInfoWindow] = new MarketRuneInfoWindow();
            mWidowDic[EWindowType.EWT_VIPPrerogativeWindow] = new VIPPrerogativeWindow();
            mWidowDic[EWindowType.EWT_RuneEquipWindow] = new RuneEquipWindow();
            mWidowDic[EWindowType.EWT_DaliyBonusWindow] = new DaliyBonusWindow();
            mWidowDic[EWindowType.EWT_EquipmentWindow] = new EquipmentWindow();
            mWidowDic[EWindowType.EWT_SystemNoticeWindow] = new SystemNoticeWindow();
            mWidowDic[EWindowType.EWT_TimeDownWindow] = new TimeDownWindow();
            mWidowDic[EWindowType.EWT_RuneCombineWindow] = new RuneCombineWindow();
			mWidowDic[EWindowType.EWT_HeroDatumWindow] = new HeroDatumWindow();
			mWidowDic[EWindowType.EWT_RuneRefreshWindow] = new RuneRefreshWindow();
            mWidowDic[EWindowType.EWT_GamePlayGuideWindow] = new GamePlayGuideWindow();//新手引导窗体类
            mWidowDic[EWindowType.EMT_PurchaseSuccessWindow] = new PurchaseSuccessWindow();
            mWidowDic[EWindowType.EMT_GameSettingWindow] = new GameSettingWindow();
            mWidowDic[EWindowType.EMT_AdvancedGuideWindow] = new AdvancedGuideWindow();
            mWidowDic[EWindowType.EMT_ExtraBonusWindow] = new ExtraBonusWindow();
            mWidowDic[EWindowType.EMT_EnemyWindow] = new EnemyWindow();
            mWidowDic[EWindowType.EMT_HeroTimeLimitWindow] = new HeroTimeLimitWindow();
            mWidowDic[EWindowType.EMT_SkillWindow] = new SkillWindow();
            mWidowDic[EWindowType.EMT_SkillDescribleWindow] = new SkillDescribleWindow();
            mWidowDic[EWindowType.EMT_RuneBuyWindow] = new RuneBuyWindow();
            mWidowDic[EWindowType.EMT_DeathWindow] = new DeathWindow();
        }

        //获取窗口
        public BaseWindow GetWindow(EWindowType type)
        {
            if (mWidowDic.ContainsKey(type))
                return mWidowDic[type];

            return null;
        }

        //每一帧更新判断一下窗口的显示
        public void Update(float deltaTime)
        {
            foreach (BaseWindow pWindow in mWidowDic.Values)
            {
                if (pWindow.IsVisible())
                {
                    pWindow.Update(deltaTime);
                }
            }
        }

        //改变到游戏场景
        public void ChangeScenseToPlay(EScenesType front)
        {
            foreach (BaseWindow pWindow in mWidowDic.Values)
            {
                if (pWindow.GetScenseType() == EScenesType.EST_Play)
                {
                    pWindow.Init();

                    if(pWindow.IsResident())
                    {
                        pWindow.PreLoad();
                    }
                }
                else if ((pWindow.GetScenseType() == EScenesType.EST_Login) && (front == EScenesType.EST_Login))
                {
                    pWindow.Hide();
                    pWindow.Realse();

                    if (pWindow.IsResident())
                    {
                        pWindow.DelayDestory();
                    }
                }
            }
        }

        //改变场景到登陆
        public void ChangeScenseToLogin(EScenesType front)
        {
            foreach (BaseWindow pWindow in mWidowDic.Values)
            {
                if (front == EScenesType.EST_None && pWindow.GetScenseType() == EScenesType.EST_None)
                {
                    pWindow.Init();

                    if (pWindow.IsResident())//判断是否常驻
                    {
                        pWindow.PreLoad();
                    }
                }

                if (pWindow.GetScenseType() == EScenesType.EST_Login)
                {
                    pWindow.Init();

                    if (pWindow.IsResident())
                    {
                        pWindow.PreLoad();
                    }
                }
                else if ((pWindow.GetScenseType() == EScenesType.EST_Play) && (front == EScenesType.EST_Play))
                {
                    pWindow.Hide();
                    pWindow.Realse();

                    if (pWindow.IsResident())
                    {
                        pWindow.DelayDestory();
                    }
                }
            }
        }

        /// <summary>
        /// 隐藏该类型的所有Window
        /// </summary>
        /// <param name="front"></param>
        public void HideAllWindow(EScenesType front)
        {
            foreach (var item in mWidowDic)
            {
                if (front == item.Value.GetScenseType())
                {
                    Debug.Log(item.Key);
                    item.Value.Hide();
                    //item.Value.Realse();
                }
            }
        }

        public void ShowWindowOfType(EWindowType type)
        { 
            BaseWindow window;
            if(!mWidowDic.TryGetValue(type , out window))
            {
                return;
            }
            window.Show();
        }

        private Dictionary<EWindowType, BaseWindow> mWidowDic;
    }


}

 UI窗体状态基类

  public interface IGameState
    {
        GameStateType GetStateType();
        void SetStateTo(GameStateType gsType);
        void Enter();
        GameStateType Update(float fDeltaTime);
        void FixedUpdate(float fixedDeltaTime);
        void Exit();
    }

窗体状态管理类

namespace Game.GameState
{
    public enum GameStateType
    {
        GS_Continue,//继续操作
        GS_Login,
        GS_User,//用户界面
        GS_Lobby,//大厅
        GS_Room,
        GS_Hero,
        GS_Loading,
        GS_Play,
        GS_Over,
    }

    public class GameStateManager : Singleton<GameStateManager>
    {
        Dictionary<GameStateType, IGameState> gameStates;
        IGameState currentState;

        public GameStateManager()
        {
            gameStates = new Dictionary<GameStateType, IGameState>();

            IGameState gameState;

            gameState = new LoginState();
            gameStates.Add(gameState.GetStateType(), gameState);

            gameState = new UserState();
            gameStates.Add(gameState.GetStateType(), gameState);

            gameState = new LobbyState();
            gameStates.Add(gameState.GetStateType(), gameState);

            gameState = new RoomState();
            gameStates.Add(gameState.GetStateType(), gameState);

            gameState = new HeroState();
            gameStates.Add(gameState.GetStateType(), gameState);

            gameState = new LoadingState();
            gameStates.Add(gameState.GetStateType(), gameState);

            gameState = new PlayState();
            gameStates.Add(gameState.GetStateType(), gameState);

            gameState = new OverState();
            gameStates.Add(gameState.GetStateType(), gameState);
        }

        public IGameState GetCurState()
        {
            return currentState;
        }

        public void ChangeGameStateTo(GameStateType stateType)
        {
            if (currentState != null && currentState.GetStateType() != GameStateType.GS_Loading && currentState.GetStateType() == stateType)
                return;

            if (gameStates.ContainsKey(stateType))
            {
                if (currentState != null)
                {
                    currentState.Exit();
                }

                currentState = gameStates[stateType];
                currentState.Enter();
            }
        }

        public void EnterDefaultState()
        {
            ChangeGameStateTo(GameStateType.GS_Login);
        }

        public void FixedUpdate(float fixedDeltaTime)
        {
            if (currentState != null)
            {
                currentState.FixedUpdate(fixedDeltaTime);
            }
        }

        public void Update(float fDeltaTime)
        {
            GameStateType nextStateType = GameStateType.GS_Continue;
            if (currentState != null)
            {
                nextStateType = currentState.Update(fDeltaTime);
            }

            if (nextStateType > GameStateType.GS_Continue)//是否进行下一步操作为0
            {
                ChangeGameStateTo(nextStateType);
            }
        }

        public IGameState getState(GameStateType type)
        {
            if (!gameStates.ContainsKey(type))
            {
                return null;
            }
            return gameStates[type];
        }
    }
}

State 

 class LoginState : IGameState
    {
        GameStateType stateTo;

        GameObject mScenesRoot;

       // GameObject mUIRoot;
	
		public LoginState()
		{
		}

        public GameStateType GetStateType()
        {
            return GameStateType.GS_Login;
        }

        public void SetStateTo(GameStateType gs)
        {
            stateTo = gs;
        }

        public void Enter()
        {
            SetStateTo(GameStateType.GS_Continue);//设置状态

            ResourceUnit sceneRootUnit = ResourcesManager.Instance.loadImmediate(GameConstDefine.GameLogin, ResourceType.PREFAB);
            mScenesRoot = GameObject.Instantiate(sceneRootUnit.Asset) as GameObject;


            LoginCtrl.Instance.Enter();
        
            ResourceUnit audioClipUnit = ResourcesManager.Instance.loadImmediate(AudioDefine.PATH_UIBGSOUND, ResourceType.ASSET);
            AudioClip clip = audioClipUnit.Asset as AudioClip;       

                                
            AudioManager.Instance.PlayBgAudio(clip);

            EventCenter.AddListener<CEvent>(EGameEvent.eGameEvent_InputUserData, OnEvent);//用户信息不完整,跳到用户信息界面
            EventCenter.AddListener<CEvent>(EGameEvent.eGameEvent_IntoLobby, OnEvent);
            EventCenter.AddListener(EGameEvent.eGameEvent_SdkLogOff, SdkLogOff);            
        }

        private void SdkLogOff()
        {
            GameMethod.LogOutToLogin();
            SetStateTo(GameStateType.GS_Login);
        }


        public void Exit()
        {
            EventCenter.RemoveListener<CEvent>(EGameEvent.eGameEvent_InputUserData, OnEvent);
            EventCenter.RemoveListener<CEvent>(EGameEvent.eGameEvent_IntoLobby, OnEvent);
            EventCenter.RemoveListener(EGameEvent.eGameEvent_SdkLogOff, SdkLogOff);       

            //LoadUiResource.DestroyLoad(mUIRoot);
            LoginCtrl.Instance.Exit();//通过广播消息,通过界面关闭
            GameObject.DestroyImmediate(mScenesRoot);            
        }

        public void FixedUpdate(float fixedDeltaTime)
        {
            
        }

        public GameStateType Update(float fDeltaTime)
        {
            return stateTo;
        }

        public void OnEvent(CEvent evt)
        {
            UIPlayMovie.PlayMovie("cg.mp4", Color.black, 2/* FullScreenMovieControlMode.Hidden*/, 3/*FullScreenMovieScalingMode.Fill*/);
            switch (evt.GetEventId())
            {
                case EGameEvent.eGameEvent_InputUserData:
                    SetStateTo(GameStateType.GS_User);//设置状态
                    break;
                case EGameEvent.eGameEvent_IntoLobby:
                    GameStateManager.Instance.ChangeGameStateTo(GameStateType.GS_Lobby);
                    break;
            }
        }
    }

modol

namespace Game.Ctrl
{
    public class LoginCtrl : Singleton<LoginCtrl>
    {
        public void Enter()
        {
            EventCenter.Broadcast(EGameEvent.eGameEvent_LoginEnter);

            SdkLink();//对应的发布平台
        }

        public void Exit()
        {
            EventCenter.Broadcast(EGameEvent.eGameEvent_LoginExit);//隐藏窗口
        }

        //登陆
        public void Login(string account, string pass)
        {
            //设置用户名和密码
            SelectServerData.Instance.SetServerInfo((int)SdkManager.Instance.GetPlatFrom(), account, pass);
            //网络先切断,再连接
            NetworkManager.Instance.canReconnect = false;
            NetworkManager.Instance.Close();

            NetworkManager.Instance.Init(GameLogic.Instance.LoginServerAdress,GameLogic.Instance.LoginServerPort, NetworkManager.ServerType.LoginServer);
        }

        //登陆错误反馈
        public void LoginError(int code)
        {
            MsgInfoManager.Instance.ShowMsg(code);
            EventCenter.Broadcast<EErrorCode>(EGameEvent.eGameEvent_LoginError, (EErrorCode)code);
        }

        //接收GateServer信息
        public void RecvGateServerInfo(Stream stream)
        {
            BSToGC.AskGateAddressRet pMsg = ProtoBuf.Serializer.Deserialize<BSToGC.AskGateAddressRet>(stream);
            SelectServerData.Instance.GateServerAdress = pMsg.ip;
            SelectServerData.Instance.GateServerPort = pMsg.port;
            SelectServerData.Instance.GateServerToken = pMsg.token;
            SelectServerData.Instance.SetGateServerUin(pMsg.user_name);
            NetworkManager.Instance.canReconnect = false;
            NetworkManager.Instance.Close();
            NetworkManager.Instance.Init(pMsg.ip, pMsg.port, NetworkManager.ServerType.GateServer); 

            EventCenter.Broadcast(EGameEvent.eGameEvent_LoginSuccess);
        }

        //登陆失败
        public void LoginFail()
        {
            NetworkManager.Instance.canReconnect = false;
            EventCenter.Broadcast(EGameEvent.eGameEvent_LoginFail);
        }

        //选择LoginServer
        public void SelectLoginServer(int i)
        {
            string ip = GameLogic.Instance.ipList.ElementAt(i);
            GameLogic.Instance.LoginServerAdress = ip;
        }

        //更新服务器列表
        public void UpdateServerAddr(Stream stream)
        {
            LSToGC.ServerBSAddr pMsg = ProtoBuf.Serializer.Deserialize<LSToGC.ServerBSAddr>(stream);

            SelectServerData.Instance.Clean();
            for (int i = 0; i < pMsg.serverinfo.Count; i++)
            {
                string addr = pMsg.serverinfo.ElementAt(i).ServerAddr;
                int state = pMsg.serverinfo.ElementAt(i).ServerState;
                string name = pMsg.serverinfo.ElementAt(i).ServerName;
                int port = pMsg.serverinfo.ElementAt(i).ServerPort;
                SelectServerData.Instance.SetServerList(i, name, (SelectServerData.ServerState)state, addr, port);
            }
            
            NetworkManager.Instance.Close();
            NetworkManager.Instance.canReconnect = false;

            SelectServerData.Instance.SetDefaultServer();

            EventCenter.Broadcast(EGameEvent.eGameEvent_SdkServerCheckSuccess);
        }

        //选择服务器
        public void SelectServer(int id)
        {
            SelectServerData.Instance.SetSelectServer(id);
            EventCenter.Broadcast(EGameEvent.eGameEvent_SelectServer); 
        }

        //开始游戏
        public void GamePlay()
        {
            int index = SelectServerData.Instance.curSelectIndex;
            SelectServerData.ServerInfo info = SelectServerData.Instance.GetServerDicInfo().ElementAt(index).Value;
            NetworkManager.Instance.canReconnect = false;
            NetworkManager.Instance.Close();
            NetworkManager.Instance.Init(info.addr, info.port, NetworkManager.ServerType.BalanceServer);
            PlayerPrefs.SetString(SelectServerData.serverKey, info.name);
        }

        //SD注册成功
        public void SdkRegisterSuccess(string name, string passWord) 
        {

            SelectServerData.Instance.SetServerInfo((int)SdkManager.Instance.GetPlatFrom(), name, passWord);

            NetworkManager.Instance.canReconnect = false;
            NetworkManager.Instance.Close();
            NetworkManager.Instance.Init(GameLogic.Instance.LoginServerAdress, GameLogic.Instance.LoginServerPort, NetworkManager.ServerType.LoginServer);                      
        }

        //SDK注消
        public void SdkLogOff()
        {
        //    NetworkManager.Instance.canReconnect = false;
        //    NetworkManager.Instance.Close();
            EventCenter.Broadcast(EGameEvent.eGameEvent_SdkLogOff);

            SdkLink();            
        }

        // 连接SDK
        public void SdkLink()
        {
            Debugger.Log("----sdk link----");

            
            #if UNITY_STANDALONE_WIN || UNITY_EDITOR || SKIP_SDK
            #else
                if (!SdkConector.islink)
                {
                       SdkConector.islink = true;
                       SdkConector.isLogOut = false;
                       SdkConector.Logout(1);
                } 
#endif
        }

   }
}

 

登陆界面

 public class LoginWindow : BaseWindow
    {
        public LoginWindow() 
        {
            mScenesType = EScenesType.EST_Login;//初始化场景类型
            mResName = GameConstDefine.LoadGameLoginUI;//资源的名字
            mResident = false;//不是常驻内存
        }

        继承接口/
        //类对象初始化
        public override void Init()
        {
            EventCenter.AddListener(EGameEvent.eGameEvent_LoginEnter, Show);
            EventCenter.AddListener(EGameEvent.eGameEvent_LoginExit, Hide);
        }

        //类对象释放
        public override void Realse()
        {
            EventCenter.RemoveListener(EGameEvent.eGameEvent_LoginEnter, Show);
            EventCenter.RemoveListener(EGameEvent.eGameEvent_LoginExit, Hide);
        }

        //窗口控件初始化,面板中有哪些button
        protected override void InitWidget()
        {
            mLoginParent = mRoot.FindChild("Server_Choose");
            mLoginInput = mRoot.FindChild("Server_Choose/Loginer");
            mLoginSubmit = mRoot.FindChild("Server_Choose/Button");
            mLoginAccountInput = mRoot.FindChild("Server_Choose/Loginer/AcountInput").GetComponent<UIInput>();
            mLoginPassInput = mRoot.FindChild("Server_Choose/Loginer/PassInput").GetComponent<UIInput>();

            mPlayParent = mRoot.Find("LoginBG");
            mPlaySubmitBtn = mRoot.Find("LoginBG/LoginBtn");//开始游戏按钮
            mPlayServerBtn = mRoot.Find("LoginBG/CurrentSelection");
            mPlayNameLabel = mRoot.FindChild("LoginBG/CurrentSelection/Label3").GetComponent<UILabel>();
            mPlayStateLabel = mRoot.FindChild("LoginBG/CurrentSelection/Label4").GetComponent<UILabel>();
            mPlayAnimate = mPlaySubmitBtn.GetComponent<Animator>();

            mChangeAccountBtn = mRoot.FindChild("ChangeAccount");
            mChangeAccountName = mRoot.FindChild("ChangeAccount/Position/Label1").GetComponent<UILabel>();

            mServerParent = mRoot.FindChild("UIGameServer");

            mReLoginParent = mRoot.FindChild("LogInAgain");
            mReLoginSubmit = mRoot.FindChild("LogInAgain/Status1/Button");

            mVersionLable = mRoot.FindChild("Label").GetComponent<UILabel>();
            mWaitingParent = mRoot.FindChild("Connecting");


            UIEventListener.Get(mPlaySubmitBtn.gameObject).onClick += OnPlaySubmit;
            UIEventListener.Get(mPlayServerBtn.gameObject).onClick += OnPlayServer;

            UIEventListener.Get(mChangeAccountBtn.gameObject).onClick += OnChangeAccount;

            UIEventListener.Get(mReLoginSubmit.gameObject).onClick += OnReLoginSubmit;

            UIEventListener.Get(mLoginSubmit.gameObject).onClick += OnLoginSubmit;

            mServerList.Clear();
            for (int i = 0; i < 4; i++)
            {
                UIToggle toggle = mLoginParent.FindChild("Server" + (i + 1).ToString()).GetComponent<UIToggle>();
                mServerList.Add(toggle);
            }

            for (int i = 0; i < mServerList.Count; i++)
            {
                EventDelegate.Add(mServerList.ElementAt(i).onChange, OnSelectIp);
            }


            DestroyOtherUI();
        }

        //删除Login外其他控件,例如
        public static void DestroyOtherUI()
        {
            Camera camera = GameMethod.GetUiCamera;
            for (int i = 0; i < camera.transform.childCount; i++)
            {
                if (camera.transform.GetChild(i) != null && camera.transform.GetChild(i).gameObject != null)
                {

                    GameObject obj = camera.transform.GetChild(i).gameObject;
                    if (obj.name != "UIGameLogin(Clone)")
                    {
                        GameObject.DestroyImmediate(obj);
                    }                    
                }
            }
        }

        //窗口控件释放
        protected override void RealseWidget()
        {
        }

        //游戏事件注册
        protected override void OnAddListener()
        {
            EventCenter.AddListener<EErrorCode>(EGameEvent.eGameEvent_LoginError, LoginFail);//登錄反饋
            EventCenter.AddListener(EGameEvent.eGameEvent_LoginSuccess, LoginSuceess);
            EventCenter.AddListener<string,string>(EGameEvent.eGameEvent_SdkRegisterSuccess, SdkRegisterSuccess);//sdk register success
            EventCenter.AddListener(EGameEvent.eGameEvent_SdkServerCheckSuccess, SdkServerCheckSuccess);//sdk register success
            EventCenter.AddListener(EGameEvent.eGameEvent_SelectServer, SelectServer);//选择了服务器
            EventCenter.AddListener(EGameEvent.eGameEvent_LoginFail, ShowLoginFail);
            EventCenter.AddListener(EGameEvent.eGameEvent_SdkLogOff, SdkLogOff);//点击了切换账号按钮
        }

        //游戏事件注消
        protected override void OnRemoveListener()
        {
            EventCenter.RemoveListener<EErrorCode>(EGameEvent.eGameEvent_LoginError, LoginFail);
            EventCenter.RemoveListener<string,string>(EGameEvent.eGameEvent_SdkRegisterSuccess, SdkRegisterSuccess);
            EventCenter.RemoveListener(EGameEvent.eGameEvent_SdkServerCheckSuccess, SdkServerCheckSuccess);
            EventCenter.RemoveListener(EGameEvent.eGameEvent_SelectServer, SelectServer);
            EventCenter.RemoveListener(EGameEvent.eGameEvent_LoginFail, ShowLoginFail);
            EventCenter.RemoveListener(EGameEvent.eGameEvent_LoginSuccess, LoginSuceess);
            EventCenter.RemoveListener(EGameEvent.eGameEvent_SdkLogOff, SdkLogOff);
        }

        //显示
        public override void OnEnable()
        {
            mVersionLable.text = SdkConector.GetBundleVersion();
            mPlayAnimate.enabled = true;
            ShowServer(LOGINUI.None);

#if UNITY_STANDALONE_WIN || UNITY_EDITOR || SKIP_SDK
            mLoginInput.gameObject.SetActive(true);
#endif
        }

        //隐藏
        public override void OnDisable()
        {
        }

        开始游戏

        void OnPlaySubmit(GameObject go)
        {
            mWaitingParent.gameObject.SetActive(true);
            UIEventListener.Get(mPlaySubmitBtn.gameObject).onClick -= OnPlaySubmit;

            LoginCtrl.Instance.GamePlay();
        }

        void OnPlayServer(GameObject go)
        {
            ShowServer(LOGINUI.SelectServer);
        }

        void OnChangeAccount(GameObject go)
        {
            LoginCtrl.Instance.SdkLogOff();
        }

        void OnReLoginSubmit(GameObject go)
        {
            mReLoginParent.gameObject.SetActive(false);

            LoginCtrl.Instance.SdkLogOff();
        }

        //点击登录提交
        void OnLoginSubmit(GameObject go)
        {
#if UNITY_STANDALONE_WIN
            if (string.IsNullOrEmpty(mLoginAccountInput.value))//判断账号是否为空
                return;
            mLoginPassInput.value = "123";
#else
           if (string.IsNullOrEmpty(mLoginAccountInput.value) || string.IsNullOrEmpty(mLoginPassInput.value))
                return;
#endif


            mWaitingParent.gameObject.SetActive(true);

            LoginCtrl.Instance.Login(mLoginAccountInput.value, mLoginPassInput.value);//验证登录名和登录密码
        }

        void OnSelectIp()
        {
            if (UIToggle.current == null || !UIToggle.current.value)
                return;
            for (int i = 0; i < mServerList.Count; i++)
            {
                if (mServerList.ElementAt(i) == UIToggle.current)
                {
                    LoginCtrl.Instance.SelectLoginServer(i);
                    break;
                }
            }
        }


        游戏事件响应

        //登录失败
        void LoginFail(EErrorCode errorCode)
        {
            mPlayAnimate.enabled = true;

            mPlaySubmitBtn.gameObject.SetActive(true);
            GameObject.DestroyImmediate(mPlayEffect.gameObject);
        }

        //登陆失败反馈
        void ShowLoginFail()
        {
            mReLoginParent.gameObject.SetActive(true);
            mWaitingParent.gameObject.SetActive(false);
            UIEventListener.Get(mPlaySubmitBtn.gameObject).onClick += OnPlaySubmit;
        }

        //登陆成功
        void LoginSuceess()
        {
            UIEventListener.Get(mPlaySubmitBtn.gameObject).onClick -= OnPlaySubmit;
        }

        //选择了服务器
        void SelectServer()
        {
            ShowSelectServerInfo();
            ShowServer(LOGINUI.Login);
        }

        //显示服务器信息或者显示登录信息
        void ShowServer(LOGINUI state)
        {
            bool showLogin = false;
            bool showServer = false;
            bool showSelectServer = false;
            switch (state)
            {
                case LOGINUI.Login:
                    ShowSelectServerInfo();
                    showLogin = true;
                    showServer = false;
                    showSelectServer = false;
                    break;
                case LOGINUI.SelectServer:
                    showLogin = false;
                    showServer = true;
                    showSelectServer = false;
                    break;
                case LOGINUI.None:
                    showLogin = false;
                    showServer = false;
#if UNITY_STANDALONE_WIN || UNITY_EDITOR || SKIP_SDK
                    showSelectServer = true;
#endif
                    break;
            }
            mPlayParent.gameObject.SetActive(showLogin);
            mServerParent.gameObject.SetActive(showServer);
            mLoginParent.gameObject.SetActive(showSelectServer);
            if (showLogin)
            {
#if UNITY_STANDALONE_WIN || UNITY_EDITOR|| SKIP_SDK
                mChangeAccountName.text = mLoginAccountInput.value;
#else
                mChangeAccountName.text = SdkConector.NickName();
#endif
            }
            mChangeAccountBtn.gameObject.SetActive(showLogin);
        }

        //显示选中的server信息 
        void ShowSelectServerInfo()
        {
            SelectServerData.ServerInfo info = SelectServerData.Instance.curSelectServer;
            mPlayNameLabel.text = info.name;
            mPlayStateLabel.text = "(" + SelectServerData.Instance.StateString[(int)info.state] + ")";
            SelectServerData.Instance.SetLabelColor(mPlayStateLabel, info.state);
        }

        //SDK注册成功
        void SdkRegisterSuccess(string uid, string sessionId)
        {
            LoginCtrl.Instance.SdkRegisterSuccess(uid, sessionId);

            mWaitingParent.gameObject.SetActive(true);
        }

        //SDK检查成功
        void SdkServerCheckSuccess()
        {
            ShowServer(LOGINUI.Login);
            mWaitingParent.gameObject.SetActive(false);

            #if UNITY_STANDALONE_WIN || UNITY_EDITOR|| SKIP_SDK
            #else
                SdkConector.ShowToolBar(0);
            #endif
        }

        //SDK退出,//改变登录状态,同时将账号和密码置空
        void SdkLogOff()
        {
            
            ShowServer(LOGINUI.None);

            mLoginPassInput.value = "";
            mLoginAccountInput.value = "";
        }

        IEnumerator ShakeLabel()
        {
            mPlayEffect = GameMethod.CreateWindow(GameConstDefine.LoadGameLoginEffectPath, new Vector3(-5, -270, 0), mRoot.transform);
            mPlaySubmitBtn.gameObject.SetActive(false);
            yield return new WaitForSeconds(1.4f);
        }
        
        enum LOGINUI
        {
            None = -1,
            Login,
            SelectServer,
        }

        //开始
        Transform mPlayParent;
        Transform mPlaySubmitBtn;
        Transform mPlayServerBtn;
        UILabel mPlayNameLabel;
        UILabel mPlayStateLabel;
        Animator mPlayAnimate;
        GameObject mPlayEffect;

        //登录
        Transform mLoginParent;
        Transform mLoginInput;
        Transform mLoginSubmit;
        UIInput mLoginPassInput;
        UIInput mLoginAccountInput;

        //改变帐号
        Transform mChangeAccountBtn;
        UILabel mChangeAccountName;

        //选服
        Transform mServerParent;

        //重新登录选择
        Transform mReLoginParent;
        Transform mReLoginSubmit;

        //等待中
        Transform mWaitingParent;

        //版本号   
        UILabel mVersionLable;

        //服务器列表
        private List<UIToggle> mServerList = new List<UIToggle>();

    }

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值