对象池
来源:互联网 发布:java怎么操作mysql 编辑:程序博客网 时间:2024/05/16 04:37
using UnityEngine;using System.Collections;using System.Collections.Generic;public enum ObjectType//两种子弹的枚举{ cubeBullet, sphereBullet,}public class MyPool : MonoBehaviour { //定义单例,方便调用 private static MyPool poolInstance; //生成对象预设体 public GameObject cubeBulletPrefab; public GameObject sphereBulletPrefab; //对象类型与预设体的映射关系 private Dictionary<ObjectType,GameObject> typeMatchPrefab=new Dictionary<ObjectType,GameObject>(); private Dictionary<ObjectType, List<GameObject>> pool = new Dictionary<ObjectType, List<GameObject>>(); public static MyPool PoolInstance { get { return MyPool.poolInstance; } }void Start () { poolInstance = this; typeMatchPrefab.Add(ObjectType.cubeBullet,cubeBulletPrefab); typeMatchPrefab.Add(ObjectType.sphereBullet,sphereBulletPrefab);} public GameObject GetObjectInPool(ObjectType ot,Vector3 pos) { GameObject go; //先判断池子中是否有该类型的小池子,并且小池子中是否有对象存在 if (pool.ContainsKey(ot) && pool[ot].Count > 0) { go = pool[ot][0];//取出池子中的第一个对象 pool[ot].RemoveAt(0);//池子中移除该对象 go.SetActive(true);//激活对象 } //若没有该类型的小池子,或者小池子没有对象,则实例化一个游戏对象给它 else { go= GameObject.Instantiate(typeMatchPrefab[ot])as GameObject; } go.transform.position = pos; return go; } public void PushPool(ObjectType ot,GameObject go) { //取消激活对象 go.SetActive(false); //判断池子中是否有该子池子,没有则创建一个,放进去 if (pool.ContainsKey(ot)) { pool[ot].Add(go); } else { pool[ot] = new List<GameObject> { go }; } }}using UnityEngine;using System.Collections;public class MyFight : MonoBehaviour { public Transform cubeBulletStartPos; public Transform sphereBulletStartPos; public float force = 15f;void Update () { if (Input.GetMouseButtonDown(0)) { GameObject go = MyPool.PoolInstance.GetObjectInPool(ObjectType.cubeBullet, cubeBulletStartPos.position); go.GetComponent<Rigidbody>().AddForce(force * go.transform.forward); StartCoroutine(DestroyObject(ObjectType.cubeBullet, go)); } if (Input.GetMouseButtonDown(1)) { GameObject go = MyPool.PoolInstance.GetObjectInPool(ObjectType.sphereBullet, sphereBulletStartPos.position); go.GetComponent<Rigidbody>().AddForce(force * go.transform.forward); StartCoroutine(DestroyObject(ObjectType.sphereBullet, go)); }} public IEnumerator DestroyObject(ObjectType ot, GameObject go) { yield return new WaitForSeconds(1f); go.GetComponent<Rigidbody>().velocity = Vector3.zero; MyPool.PoolInstance.PushPool(ot, go); }}
0 0
- 对象池
- 对象池
- 对象池
- 对象池
- 对象池
- 对象池
- 对象池
- 对象池
- 对象池
- 对象池
- 对象池
- 对象池
- 对象池
- 对象池
- 对象池
- 对象池
- 对象池
- 对象池
- c——复合类型——struct union 内存对齐
- spring与mybatis三种整合方法
- java语言求最小公倍数和最大公约数的三种算法
- solr集群搭建
- Handler、looper、Message之间的关系?
- 对象池
- 程序员面试金典——解题总结: 9.17中等难题 17.8给定一个整数数组(有正数有负数),找出总和最大的连续数列,并返回总和
- 【Unity&NGUI】我的背包系统相关文章总览
- align与valign区别
- AFNetworking3.1.0源码分析(十三)AFURLSessionManager
- HDU-3555Bomb 数位dp
- Cocos2d-x下Lua调用自定义C++类
- github最基础使用技能
- imx6q 定时器设置