提取基类共性 BaseWindow
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;
}
}
Awake>OnEnble>Start
LoginWindow
管理类WindowManager中注册所有窗体 MainWindow
HeroWindow
Show()方法:Creat(),Init(),OnEnable()点击时间注册回调,AddLisener()事件监听
ReleaseWidget()释放内存,Destory 破坏掉
预加载preload()
LoadUIResource()
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>();
}
//传入Resources下相对路径名称 例如Resources/Game/Effect1 传入Game/Effect1
public ResourceUnit loadImmediate(string filePathName, ResourceType resourceType, string archiveName = "Resources")
{
//使用assetbundle打包
if (UsedAssetBundle)
{
//添加Resource
string completePath = "Resources/" + filePathName;
string completeName = ArchiveManager.Instance.getPath("Resources", completePath);
//根据场景名称获取asset信息
AssetInfo sceneAssetInfo = mAssetInfoManager.GetAssetInfo(completeName);
//获取依赖的asset的索引
foreach (int index in sceneAssetInfo.mDependencys)
{
//根据索引获取依赖的Asset
AssetInfo depencyAsset = mAssetInfoManager.GetAssetInfo(index);
string depencyAssetName = depencyAsset.mName;
//加载场景依赖assetbundle
_LoadImmediate(depencyAssetName, ResourceType.ASSET);
}
//加载本身预制件
ResourceUnit unit = _LoadImmediate(completeName, resourceType);
return unit;
}
//不使用
else
{
Object asset = Resources.Load(filePathName);
ResourceUnit resource = new ResourceUnit(null, 0, asset, null, resourceType);
return resource;
}
}
下载过程中断网,根据资源大小判断
ResourceUnit
namespace Game.Resource
{
public enum ResourceType
{
ASSET,
PREFAB,
LEVELASSET,
LEVEL,
}
public class ResourceUnit : IDisposable//托管便于释放内存
{
private string mPath;
private Object mAsset;
private ResourceType mResourceType;
private List<ResourceUnit> mNextLevelAssets;
private AssetBundle mAssetBundle;
private int mAssetBundleSize;
private int mReferenceCount;
//private int mAllDependencesAssetSize;
internal ResourceUnit(AssetBundle assetBundle, int assetBundleSize, Object asset, string path, ResourceType resourceType/*, int allDependencesAssetSize*/)
{
mPath = path;
mAsset = asset;
mResourceType = resourceType;
mNextLevelAssets = new List<ResourceUnit>();
mAssetBundle = assetBundle;
mAssetBundleSize = assetBundleSize;
mReferenceCount = 0;
//mAllDependencesAssetSize = allDependencesAssetSize;
}
public Object Asset
{
get
{
return mAsset;
}
internal set
{
mAsset = value;
}
}
public ResourceType resourceType
{
get
{
return mResourceType;
}
}
public List<ResourceUnit> NextLevelAssets
{
get
{
return mNextLevelAssets;
}
internal set
{
foreach (ResourceUnit asset in value)
{
mNextLevelAssets.Add(asset);
}
}
}
public AssetBundle Assetbundle
{
get
{
return mAssetBundle;
}
set
{
mAssetBundle = value;
}
}
public int AssetBundleSize
{
get
{
return mAssetBundleSize;
}
}
public int ReferenceCount
{
get
{
return mReferenceCount;
}
}
//public int AllDependencesAssetSize
//{
// get
// {
// return mAllDependencesAssetSize;
// }
//}
public void dumpNextLevel()
{
string info = mPath + " the mReferenceCount : " + mReferenceCount + "\n";
foreach (ResourceUnit ru in mNextLevelAssets)
{
ru.dumpNextLevel();
info += ru.mPath + "\n";
}
DebugEx.Log(info, ResourceCommon.DEBUGTYPENAME);
}
public void addReferenceCount()
{
++mReferenceCount;
foreach (ResourceUnit asset in mNextLevelAssets)
{
asset.addReferenceCount();
}
}
public void reduceReferenceCount()
{
--mReferenceCount;
foreach (ResourceUnit asset in mNextLevelAssets)
{
asset.reduceReferenceCount();
}
if (isCanDestory())
{
//ResourcesManager.Instance.mLoadedResourceUnit.Remove(ResourceCommon.getFileName(mPath, true));
Dispose();
}
}
public bool isCanDestory() { return (0 == mReferenceCount); }
public void Dispose()
{
ResourceCommon.Log("Destory " + mPath);
if (null != mAssetBundle)
{
//mAssetBundle.Unload(true);
mAssetBundle = null;
}
mNextLevelAssets.Clear();
mAsset = null;
}
}
}
LoginWindow,类不挂在窗体上,程序和美术分离不相干
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>();
}
Singleton单例
public abstract class Singleton<T> where T : new()
{
private static T _instance;
static object _lock = new object();
public static T Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
_instance = new T();
}
}
return _instance;
}
}
}
public class UnitySingleton<T> : MonoBehaviour
where T : Component
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType(typeof(T)) as T;
if (_instance == null)
{
GameObject obj = new GameObject();
//obj.hideFlags = HideFlags.DontSave;
obj.hideFlags = HideFlags.HideAndDontSave;
_instance = (T)obj.AddComponent(typeof(T));
}
}
return _instance;
}
}
public virtual void Awake()
{
DontDestroyOnLoad(this.gameObject);
if (_instance == null)
{
_instance = this as T;
}
else
{
Destroy(gameObject);
}
}
}
ChangeScenseToPlay() 2D转3D场景调用
ChangeScenseToLogin() 3D转2D调用