unity对象池示例代码

Posted lucater

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了unity对象池示例代码相关的知识,希望对你有一定的参考价值。

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 
 5 public class ObjectPool : MonoBehaviour {
 6     public static ObjectPool instance;
 7     Dictionary<string, Stack<GameObject>> pools = new Dictionary<string, Stack<GameObject>>();
 8     //Stack<GameObject> pool=new Stack<GameObject>();
 9     void Start () {
10         instance = this;
11 
12     }
13     public void Delete(string key,GameObject g)
14     {
15         g.SetActive(false);
16         pools[key].Push(g);
17     }
18     public GameObject Creat(string key,GameObject prefab,Vector3 position,Quaternion qua)
19     {
20         GameObject g=null;
21         if (pools.ContainsKey(key))
22         {
23             if (pools[key].Count > 0)
24             {
25                 g = pools[key].Pop();
26                 g.SetActive(true);
27                 g.transform.position = position;
28                 g.transform.rotation = qua;
29             }
30             else
31             {
32                 g = Instantiate(prefab, position, qua);
33             }
34         }
35         else
36         {
37             pools.Add(key, new Stack<GameObject>());
38             g = Instantiate(prefab, position, qua);
39 
40         }
41         return g;
42     }
43     void Update () {
44         
45     }
46 }
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PoolTest : MonoBehaviour {
    public GameObject[] prefab;
    public Stack<GameObject> s=new Stack<GameObject>();
    public int set = 0;
    void Start () {
        
    }
    public void Creat()
    {
        s.Push(ObjectPool.instance.Creat(set.ToString(),prefab[set], Vector3.one, Quaternion.identity));
    }
    public void Delete()
    {
        ObjectPool.instance.Delete(set.ToString(),s.Pop());
    }
    void Update () {
        
    }
}

 

以上是关于unity对象池示例代码的主要内容,如果未能解决你的问题,请参考以下文章

Unity3D-对象池

Unity3D-对象池

Unity3D-对象池

Unity内存优化和内存池使用实践

Unity对象池试水

Unity 游戏框架搭建 (二十一) 使用对象池时的一些细节