对象池Demo

CreateHit Screen.cs


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

public class CreateHitScreen : MonoBehaviour
{
    public Transform panel;
    
    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
            {
                if (hit.collider.CompareTag("Player"))
                {
                    Cube cubeTemp = hit.collider.GetComponent<Cube>();
                    if (cubeTemp)
                    {
                        cubeTemp.Hide();
                        PoolMananger.instance.DelayDespawn(cubeTemp.gameObject,.5f);
                    }
                }
                else
                {
                    CreateCube(hit.point + Vector3.up*1.2f);
                }
            }
            else
            {
                CreateCube(ScreenPosToWorldPos(panel.position,Input.mousePosition));
            }
        }
        
        if (Input.GetMouseButtonDown(1))
        {
            RaycastHit hit;
            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
            {
                if (hit.collider.CompareTag("Player"))
                {
                    Cube cubeTemp = hit.collider.GetComponent<Cube>();
                    if (cubeTemp)
                    {
                        //cubeTemp.Hide();
                        PoolMananger.instance.DelayDespawn(cubeTemp.gameObject,.5f);
                    }
                }
                else
                {
                    CreateCube(hit.point + Vector3.up*1.2f,true);
                }
            }
            else
            {
                CreateCube(ScreenPosToWorldPos(panel.position,Input.mousePosition),true);
            }
        }
    }
    

    public void CreateCube(Vector3 pos,bool directly = false)
    {
        GameObject obj = PoolMananger.instance.SpawnFromPool(directly?"cube2":"cube", pos, Quaternion.identity);

        if (obj != null)
        {
            Cube cubeTemp = obj.GetComponent<Cube>();
            if(!directly)
                cubeTemp.Show();
        }
    }
    

    static Vector3 ScreenPosToWorldPos(Vector3 referencePosition, Vector2 screenPos)
    {
        //1.将世界坐标转换为屏幕坐标,获取参考值z
        Vector3 refeScreenPos = Camera.main.WorldToScreenPoint(referencePosition);
        
        //2.屏幕坐标和 z 值组成新的坐标 再转换会世界坐标
        Vector3 screenNewPos = new Vector3(screenPos.x,screenPos.y,refeScreenPos.z);

        return Camera.main.ScreenToWorldPoint(screenNewPos);
    }
}
 

预制体对象Cube.cs


// 在这里编写代码using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;

public class Cube : MonoBehaviour
{

   public AnimationCurve showAnimationCurve,hideAnimationCurve;

   public bool isAnim;

   /// <summary>
   /// 显示
   /// </summary>
   public void Show()
   {
      transform.DOKill();
      transform.localScale = Vector3.zero;;
      if (isAnim)
      {
         transform.DOScale(Vector3.one, .5f).SetEase(showAnimationCurve);
      }
      else
      {
         transform.DOScale(Vector3.one, .5f).SetEase(Ease.OutBounce);
      }
      
   }

   /// <summary>
   /// 隐藏
   /// </summary>
   public void Hide(float duration = .5f)
   {
      transform.DOKill();
      if (isAnim)
      {
         transform.DOScale(Vector3.zero, duration).SetEase(hideAnimationCurve);
      }
      else
      {
         transform.DOScale(Vector3.zero, duration).SetEase(Ease.InBounce);
      }
   }
}
 

PoolMananger .cs

开始生成指定数量的对象,方便后续拿取放回


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

/// <summary>ger
/// 对象池
/// </summary>
public class PoolMananger : MonoBehaviour
{
    [System.Serializable]
    public class Pool
    {
        public string tag;
        public GameObject prefab;
        public int size;
    }
    
    /// <summary>
    /// 单例
    /// </summary>
    public static PoolMananger instance;
    
    [Header("根节点")] public Transform rootTran;
    public List<Pool> pools;

    public Dictionary<string, QueueGameObject<>> poolDictionary;
    
    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        InstantiatePool();
    }

    /// <summary>
    /// 初始化生成
    /// </summary>
    public void InstantiatePool()
    {
        poolDictionary = new Dictionary<string, Queue<GameObject>>();

        foreach (Pool pool in pools)
        {
            Queue<GameObject> objectQueue = new Queue<GameObject>();

            for (int i = 0; i < pool.size; i++)
            {
                GameObject obj = Instantiate(pool.prefab, rootTran);
                obj.SetActive(false);
                objectQueue.Enqueue(obj);
            }
            poolDictionary.Add(pool.tag, objectQueue);
        }
    }

    /// <summary>
    /// 从对象池中生成物体
    /// </summary>
    /// <param name="tag">标签</param>
    /// <param name="position"></param>
    /// <param name="rotation"></param>
    /// <returns></returns>
    public GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation)
    {
        if (!poolDictionary.ContainsKey(tag))
        {
            Debug.LogWarning("Pool with tag "+tag+" doesn't exist!");
            return null;
        }
        
        GameObject objectToSpawn = null;
        for (int i = 0; i < poolDictionary[tag].Count; i++)
        {
            objectToSpawn = poolDictionary[tag].Dequeue();
            poolDictionary[tag].Enqueue(objectToSpawn);
            if (objectToSpawn.activeSelf == false)//遍历,有未激活的,就激活
            {
                objectToSpawn.SetActive(true);
                objectToSpawn.transform.position = position;
                objectToSpawn.transform.rotation = rotation;
                return objectToSpawn;
            }
        }

        return null;//没有找到未激活的,return null
    }
    
    /// <summary>
    /// 全部回收对象池
    /// </summary>
    /// <param name="tag"></param>
    public void DeSpawnToPool(string tag)
    {
        if (!poolDictionary.ContainsKey(tag))
        {
            Debug.LogWarning("Pool with tag" + tag + " doesn't exist!");
            return;
        }
        
        GameObject objectToSpawn = null;
        for (int i = 0; i < poolDictionary[tag].Count; i++)
        {
            objectToSpawn = poolDictionary[tag].Dequeue();
            poolDictionary[tag].Enqueue(objectToSpawn);
            if (objectToSpawn.activeSelf)
            {
                objectToSpawn.transform.SetParent(rootTran);
                objectToSpawn.SetActive(false);
            }
        }
    }

    
    /// <summary>
    /// 延时回收某个对象
    /// </summary>
    /// <param name="targetObj"></param>
    /// <param name="delayTime"></param>
    public void DelayDespawn(GameObject targetObj, float delayTime)
    {
        StartCoroutine(DelaySetActiveFalse(targetObj, delayTime));
    }

    
    IEnumerator DelaySetActiveFalse(GameObject g, float delayTime)
    {
        yield return new WaitForSeconds(delayTime);
        g.transform.SetParent(rootTran);
        g.SetActive(false);
    }
}



 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值