游戏蛮牛学习群(纯技术交流,不闲聊):539178957
游戏蛮牛 手机端
开启辅助访问
 找回密码
 注册帐号

扫一扫,访问微社区

首页   >   博客   >   UnityTerminator

游戏框架-对象池 热度 3

个人分类: MMO游戏设计框架 | 2018-7-5 10:17
标签:对象池
0 个评论 | 阅读 92 | 收藏 | 举报

[code]csharpcode:

using System;
using System.Collections.Generic;
using UnityEngine;

public class Pool
{
    /// <summary>
    /// 创建一个列表容器用来保存预制体对象
    /// </summary>
    private List<GameObject> _avaliables = new List<GameObject>();

    /// <summary>
    /// 生成对象的函数
    /// </summary>
    /// <param name="path"></param>
    /// <param name="name"></param>
    /// <returns></returns>
    public GameObject Spawn(string path, string name)
    {
        GameObject go = null;
        if (_avaliables.Count <= 0)
        {
            go = GameObject.Instantiate(Resources.Load(path + name)) as GameObject;
            go.name = name;
            _avaliables.Add(go);
        }
        else
        {
            go = _avaliables[0];
            go.SetActive(true);
            _avaliables.Remove(go);
        }
        return go;
    }

    /// <summary>
    /// 回收对象的函数
    /// </summary>
    /// <param name="go"></param>
    public void UnSpawn(GameObject go)
    {
        go.transform.position = new Vector3(1000, 1000, 1000);
        go.SetActive(false);
        _avaliables.Add(go);
    }

    /// <summary>
    /// 清空容器内中的对象
    /// </summary>
    public void Clear()
    {
        _avaliables.Clear();
    }
}

public class PoolManager : Singleton<PoolManager>
{
    private Dictionary<string, Pool> _pools = new Dictionary<string, Pool>();

    /// <summary>
    /// 生成预制体对象
    /// </summary>
    /// <param name="path"></param>
    /// <param name="name"></param>
    /// <returns></returns>
    public GameObject Spawn(string path, string name)
    {
        GameObject go = null;
        if (_pools.ContainsKey(name))
        {
            go = _pools[name].Spawn(path, name);
        }
        else
        {
            Pool pool = new Pool();
            go = pool.Spawn(path, name);
            _pools.Add(name, pool);
        }
        return go;
    }

    /// <summary>
    /// 回收对象
    /// </summary>
    /// <param name="go"></param>
    public void UnSpawn(GameObject go)
    {
        _pools[go.name].UnSpawn(go);
    }

    /// <summary>
    /// 清空游戏对象
    /// </summary>
    public void Clear()
    {
        foreach (Pool pool in _pools.Values)
        {
            pool.Clear();
        }
    }
}

3 0

作者的其他最新博客

评论 (0 个评论)

facelist doodle 涂鸦板

您需要登录后才可以评论 登录 | 注册帐号

个人分类

标签

阅读排行

评论排行

推荐博客

最新博客

关闭

站长推荐 上一条 /1 下一条

返回顶部