您的位置:首页 > 其它

对象池的应用的简单Demo

2015-12-02 11:35 453 查看
<span style="font-size:18px;">对象池的简单应用</span>
using UnityEngine;
using System.Collections;

public class Attack : MonoBehaviour {

void OnMouseDown()
{
//Point为发射点的空物体
GameObject o = ObjectPool.instance.GetFromPool
("Bullet",
GameObject.Find ("Point").transform.position, Quaternion.identity
);
o.transform.LookAt (GameObject.Find ("Wall").transform.position);
o.GetComponent<Rigidbody>().AddForce(Vector3.forward * 500);
}

void OnTriggerStay(Collider collider)
{
if (collider.name == "Bullet(Clone)") {
// 存之前消除速度
collider.gameObject.GetComponent
<Rigidbody> ().velocity = Vector3.zero;
ObjectPool.instance.ReturnPool (collider.gameObject);
}
}
}


首先建立一个脚本ObjectPool挂载在MainCamera上接着创建一个脚本Attack脚本,挂载在一个Cube上,将Collider的isTrigger的属性勾选,创建Bullet(注意改名)预制体,并加上刚体,放在Resources文件夹下。

这样子弹进入后就加入对象池。

using UnityEngine;
using System.Collections;

public class Attack : MonoBehaviour {

void OnMouseDown()
{
//Point为发射点的空物体
GameObject o = ObjectPool.instance.GetFromPool
("Bullet",
GameObject.Find ("Point").transform.position, Quaternion.identity
);
o.transform.LookAt (GameObject.Find ("Wall").transform.position);
o.GetComponent<Rigidbody>().AddForce(Vector3.forward * 500);
}

void OnTriggerStay(Collider collider)
{
if (collider.name == "Bullet(Clone)") {
// 存之前消除速度
collider.gameObject.GetComponent
<Rigidbody> ().velocity = Vector3.zero;
ObjectPool.instance.ReturnPool (collider.gameObject);
}
}
}


对象池的原理就是将重复利用的资源(例如:子弹)不用时不直接销毁,而是将他的active属性设置为false。当对象池中不存在物体时,创建对象。当用完该物体时,存入对象池。下次就可直接从对象池中获取,不需要再次创建。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: