初级UnityDemo全纪录(二):代码篇①

来源:互联网 发布:matlab最优化工具箱 编辑:程序博客网 时间:2024/06/05 08:51

直接上。思路和代码~~~

-## Tool(工具类) ##
- UnityAllSceneSingleton类
- 思路
因为在这些简单的项目里边,单例模式还是用的比较多的,所以,首先去创建一个单例的类,并且约束为控件。这样就能控制类的初始化和销毁顺序,很多资源方面的加载,卸载一般都能放在单例里边。
- 代码

public class UnityAllSceneSingleton<T> : MonoBehaviourwhere 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类位接口类
  • 代码
public interface IMessageObject{}public static  class MessageObject{    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 NEEDLOG        Debug.Log("end method " + t.GetType().Name +".Message:" + msg + "======");    #endif}}
  • UnitySceneSingleton类
  • 思路
    Untiy中场景也需要单例,就写一个场景中所需要的单例类,本程序可能用不到,但是加上,以后用到了就不用再添加了
  • 代码
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.HideAndDontSave;                    _instance = obj.AddComponent(typeof(T)) as T;                }            }            return _instance;        }    }}

初步的只有这些了,也是在学习阶段,请各位大大多多批评~我会好好修改的。。

0 0
原创粉丝点击