码迷,mamicode.com
首页 > 编程语言 > 详细

unity对象池示例代码

时间:2020-03-17 11:33:33      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:instant   ide   static   prefab   cti   pos   pre   ict   identity   

 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对象池示例代码

标签:instant   ide   static   prefab   cti   pos   pre   ict   identity   

原文地址:https://www.cnblogs.com/lucater/p/12509472.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!