直接上。思路和代码~~~
-## Tool(工具类) ##
- UnityAllSceneSingleton类
- 思路
因为在这些简单的项目里边,单例模式还是用的比较多的,所以,首先去创建一个单例的类,并且约束为控件。这样就能控制类的初始化和销毁顺序,很多资源方面的加载,卸载一般都能放在单例里边。
- 代码
using UnityEngine;
public class UnityAllSceneSingleton<T> : MonoBehaviour
where T : Component
{
private static T _instance;
public static T Instances
{
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);
}
}
}
MessageObject类
思路
debug,对于Unity3D来说,是很重要的一部分,我们很多时候,个人习惯写一个debug的类,去输出一些自己想要的内容,这个是一个很方便的方法。
MessageObject类位接口类
代码
using UnityEngine;
using System.Collections;
public interface IMessageObject
{
}
public static class MassageObject
{
public static void START_METHOD<T>(this T t, string MethodName) where T : IMessageObject
{
#if NEEDLOGMETHOD
Debug.Log("Start method" + t.GetType().Name + ".Method:" + MethodName + "+++++++++++++++");
#endif
}
public static void END_METHOD<T>(this T t, string MethodName) where T : IMessageObject
{
#if NEEDLOGMETHOD
Debug.Log("End method" + t.GetType().Name + ".Method:" + MethodName + "+++++++++++++++");
#endif
}
public static void PRINT<T>(this T t, string Msg) where T : IMessageObject
{
#if NEEDLOGMETHOD
Debug.Log("Method:"+t.GetType().Name + ".Message"+Msg);
#endif
}
}
UnitySceneSingleton类
思路
Untiy中场景也需要单例,就写一个场景中所需要的单例类,本程序可能用不到,但是加上,以后用到了就不用再添加了
代码
using UnityEngine;
using System.Collections;
public class UnityScenesSingleton<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.HideAndDontSave;
_Instance = obj.AddComponent(typeof(T)) as T;
}
}
return _Instance;
}
}
}
初步的只有这些了,也是在学习阶段,请各位大大多多批评~我会好好修改的。。