伪单列,单列,点击button生成不同的物体,这个里生成了两种物体
1.池子的脚本,开头注释部分是单例的,正在用的是伪单例,伪单列需要随便找个物体把脚本挂起来,单例不需要挂脚本,,也不继承任何东西:
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 public class zidianPool : MonoBehaviour//这是伪单利,需要继承MonoBehaviour 6 { 7 public static zidianPool Instence;//共有静态 8 private void Start() 9 { 10 Instence = this;//生命周期开始实例 11 } 12 //// 这是单利的,不需要继承MonoBehaviour 13 // public class zidianPool 14 //{ 15 // private static zidianPool dict;//私有静态 16 // private zidianPool() { } 17 // public static zidianPool Instence 18 // { 19 // get 20 // { 21 // dict = new zidianPool(); 22 // return dict; 23 // } 24 // } 25 26 27 Dictionary<string, List<GameObject>> dic = new Dictionary<string, List<GameObject>>();////创建池子(用于存储Cube和Sphere) 28 29 public GameObject GetPool(string name) 30 { 31 GameObject go=null;//go此时就是个容器 //一会把要拿出去的东西定义出来 32 33 if (dic.ContainsKey(name))//字典是否包含这个名字 //是否包含name的key 34 35 { 36 List < GameObject > lis= dic[name]; 37 go=lis[0]; 38 go.SetActive(true); 39 lis.RemoveAt(0); 40 } 41 if (go==null)//没有name名字的,或者list为0时 42 43 { 44 go = GameObject.Instantiate(Resources.Load(name)) as GameObject; 45 //把名字统一 46 int index = go.name.IndexOf('('); 47 go.name = go.name.Substring(0, index); 48 } 49 return go; 50 } 51 public void Save(GameObject obj) 52 { 53 //存的时候先让有的失活 54 obj.SetActive(false); 55 if (dic.ContainsKey(obj.name))//查看字典里是否包含该物体的名字 56 { 57 dic[obj.name].Add(obj);//???????????? 58 } 59 else//字典里没有key值 60 { 61 List<GameObject> list = new List<GameObject>();//创建一个list接受key值 62 list.Add(obj); 63 dic[obj.name] = list; 64 } 65 obj.transform.parent = GameObject.Find("pool").transform;//给生成的物体找一个爹 66 } 67 }
2.点击button生成物体,:
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 public class getZidianPool : MonoBehaviour { 6 string[] s = { "Sphere", "Cube" }; 7 GameObject go; 8 // Use this for initialization 9 void Start () { 10 11 } 12 public void IsGetpool() 13 { 14 go= zidianPool.Instence.GetPool(s[Random.Range(0,2)]);//有多个名字,就想到要用数组 15 go.transform.position = new Vector3(0, 4, 0); 16 } 17 // Update is called once per frame 18 void Update () { 19 20 } 21 }
3.生成出来的物体到一定位移后失活:脚本挂在本身上,再把物体传入到第一个脚本里的save:
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 public class zidianSave : MonoBehaviour { 6 7 // Use this for initialization 8 void Start () { 9 10 } 11 12 // Update is called once per frame 13 void Update () { 14 if (transform.position.y<-5) 15 { 16 zidianPool.Instence.Save(this.gameObject); 17 } 18 } 19 }





浙公网安备 33010602011771号