2021-06-15

对象池
在使用unity3d做游戏时,经常有同一个Prefab用到多次,需要反复实例化(Instantiate)。但实例化是很消耗资源的,所以在游戏加载时把一批Prefab实例化好放在对象池中,游戏中用的时候拿出来,不用的时候放回去,避免反复申请和销毁。
存入对象池的元素应具有如下特征:1>场景中大量使用 2>存在一定的生命周期,会较为频繁的申请和释放。
作用;减少内存,优化游戏流畅程度。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//对象池管理器
public class PoolTest : MonoBehaviour {
//集合
public List list = new List();
//游戏预设体
public GameObject GoPrefab;
//最大个数
public int MaxCount = 100;
// Use this for initialization
//对象保存到对象中
public void push(GameObject go)
{
if (list.Count < MaxCount)
{
list.Add(go);
}
else {
Destroy(go);
}
}
//从对象池中取出一个对象
public GameObject Pop() {
if (list.Count > 0)
{
if (list.Count > 0)
{
GameObject go = list[0];
list.RemoveAt(0);
return go;
}

    }
    return Instantiate(GoPrefab);
}
//清楚对象池
public void clera() {
    list.Clear();
}

}
1.创建一个cube,设为预设体
2.创建一个空物体,挂载PoolTest 脚本,和test脚本。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
private List list = new List();
// Use this for initialization
void Start()
{

}

// Update is called once per frame
void Update()
{

    if (Input.GetMouseButtonDown(0))
    {
        //创建
        //从对象池取出
        GameObject go = GetComponent<PoolTest>().Pop();
        go.SetActive(true);
    }
    if (Input.GetMouseButtonUp(1))
    {
        //删除
        //放入对象池
        if (list.Count > 0)
        {
            GetComponent<PoolTest>().push(list[0]);
            list[0].SetActive(false);
            list.RemoveAt(0);
           
        }
    }
}

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值