物件池的簡單實現
阿新 • • 發佈:2018-12-12
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 public class GameInstatie : MonoBehaviour { 6 7 private Stack<GameObject> GameManager = new Stack<GameObject>();//未啟用怪我的物件池 8 private Stack<GameObject> IntatiaManager = new Stack<GameObject>();//啟用怪物的物件池; 9 public Transform transform; //設定的父物體位置; 10 public GameObject Cube; //所需要例項化的物體; 11 // Use this for initialization 12 void Start () { 13 14 } 15 16 // Update is called once per frame 17 void Update () { 18 //點選滑鼠左鍵生成物體 19 if (Input.GetMouseButtonDown(0)) 20 { 21 if (GameManager.Count > 0) 22 { 23 GameObject obj = GameManager.Pop(); 24 obj.SetActive(true); 25 IntatiaManager.Push(obj); 26 Debug.Log(IntatiaManager.Count); 27 28 }29 else 30 { 31 GameObject obj = Instantiate(Cube); 32 IntatiaManager.Push(obj); 33 Debug.Log(IntatiaManager.Count); 34 } 35 } 36 //點選滑鼠右鍵把已經生成的物體回收 37 if (Input.GetMouseButtonDown(1)) 38 { 39 if (IntatiaManager.Count > 0) 40 { 41 Debug.Log(IntatiaManager.Count); 42 GameObject obj = IntatiaManager.Pop(); 43 obj.transform.SetParent(transform); 44 obj.SetActive(false); 45 GameManager.Push(obj); 46 47 } 48 49 } 50 51 52 } 53 }