這個應該屬於擼一個適合自己的小遊戲框架的第四篇。上一篇是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);
}
}
以上。