这个应该属于撸一个适合自己的小游戏框架的第四篇。上一篇是Unity网格合并,Matrix4x4,和InverseTransformPoint的简单理解。
这里在写小框架的对象池的时候。参考其他人代码的时候看到了这样的代码
public class SpawnPool
{
private string _goName = string.Empty;
//Pool中当前的对象数量
private int _nowCount;
//Pool中对象的最大数量
private int _maxCount;
private GameObject _prefab;
private Transform _parent = null;
private bool _isAutoHide = false;
private float _autoHideTimer = -1;
//显示对应的list
private List<GameObject> _trueListGo;
//隐藏物体的list
private List<GameObject> _falseListGo;
public int TrueCount { get { return this._trueListGo.Count; } }
public int FalseCount { get { return this._falseListGo.Count; } }
public SpawnPool(string _GoName,int _MaxCount, GameObject _Prefab, Transform _Tra):this(_GoName,_MaxCount,_Prefab,_Tra,false,-1)
{
}
public SpawnPool (string _GoName,int _MaxCount, GameObject _Prefab, Transform _Tra,bool _IsAutoHide,float _AutoHideTimer)
{
this._goName = _GoName;
this._parent = _Tra;
this._maxCount = _MaxCount;
this._prefab = _Prefab;
this._isAutoHide = _IsAutoHide;
this._autoHideTimer =_AutoHideTimer;
this._trueListGo = new List<GameObject>();
this._falseListGo = new List<GameObject>();
this._dicGoSurviveTimer = new Dictionary<GameObject,int>();
//每次克隆物体会+1
this._nowCount = 0;
//生成的pool时初始化一个隐藏物体。
GameObject go = this.InsGo ();
go.transform.SetParent(_Tra);
go.transform.localPosition = Vector3.zero;
this.HideGo(go);
}
}
很简单的构造函数,只是用了this关键字。通过运行发现传两种参数来调用方法都走下面6个参数的构造。
然后找到了this这种用法。用this串联构造函数。
结论如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test : MonoBehaviour {
void Start()
{
//实例化test
test test = new test("111");
test test1 = new test("222",1);
}
/// <summary>
/// 无参构造函数函数。继承MonoBehaviour。
/// 状况1:当挂载到场景中的就会执行一次。
/// 状况2:开始运行的时候会自动执行两次。
/// 状况3:关闭运行的时候会自动执行一次。
/// 结论:MonoBehaviour有两个生命周期,一个是作为C#对象的周期,
/// 一个是作为Component的周期。构造函数代表第一个,Awake代表第二个。
/// 即你的代码既可以作为Unity的脚本,也可以作为C#的脚本执行。
/// 在不同的生命周期执行会表现的跟Player环境下不一样。
/// 所以尽量不要用构造函数(很多文档都提到过这个),设计上需要用也要保证初始化代码尽可能简单。
/// </summary>
public test()
{
Debug.LogError("无参构造函数");
}
/// <summary>
/// 有参构造函数。使用this关键字
/// 状况:会先执行this后面串联的构造函数然后再执行自己的方法。
/// </summary>
/// <param name="text"></param>
public test(string text) : this(text, 0)
{
Debug.LogError("1个参数的构造函数:");
Debug.LogError("text:" + text);
}
/// <summary>
/// 有参构造函数。不使用this关键字
/// 状况:必须用包含对应参数的实例化方法才能执行。
/// </summary>
/// <param name="text"></param>
/// <param name="x"></param>
public test(string text,int x)
{
Debug.LogError("2个参数的构造函数:");
Debug.LogError("text:" + text);
Debug.LogError("x:"+x);
}
}
以上。