這樣很浪費效能 (比如說子彈之類的)
比較合理的做法可以做一個物件池
來回收資源再利用 (資源回收?)~
程式碼:
using UnityEngine;using System.Collections;using System.Collections.Generic;using System;public class ObjectPool{public Transform _parent = null;private Queue<GameObject> _pool = new Queue<GameObject>();private GameObject _prefab = null;public ObjectPool(GameObject prefab, Transform parent = null){_parent = parent;_prefab = prefab;}public GameObject Spwan(){GameObject result = null;if (_pool.Count > 0)result = _pool.Dequeue();elseresult = UnityEngine.Object.Instantiate(_prefab);result.gameObject.SetActive(true);if (_parent)result.transform.SetParent(_parent);return result;}public T Spwan<T>() where T : Component{return Spwan() as T;}public void Despwan(GameObject go){_pool.Enqueue(go);go.SetActive(false);}}
_objectPool = new ObjectPool(_prefab, _parent);
var go = _objectPool.Spwan(); -> 拿出來用 , 如果沒有的話 幫妳複製一個新的
_objectPool.Despwan(go); -> 不要用的東西丟回去池子裡
沒有留言:
張貼留言