unity对象池

一共3个类:

BulletManage:子弹管理类

BulletShooting:子弹发射类

BulletObject:子弹类

子弹发射类 向 子弹管理类 申请一个 子弹,如果子弹active为false,则表示是已经用过的子弹,可以直接使用,如果子弹active为真,则要重新创建一个新的子弹。

代码如下:

子弹管理类

using System.Collections.Generic;
using UnityEngine;

public class BulletManage : MonoBehaviour{

    private static BulletManage instance;
    public static BulletManage Get()
    {
        return instance;
    }

    void Awake()
    {
        instance = this;
        bulletObject = new List<GameObject>();
    }
    private static List<GameObject> bulletObject;
    public GameObject GetBullet()
    {
        GameObject bullet;
        foreach (var item in bulletObject)
        {
            if (item != null && item.activeSelf == false)
                return item;
        }
        bullet = Instantiate(Resources.Load("BulletPrefab")) as GameObject;
        bulletObject.Add(bullet);
        return bullet;
    }
}

子弹发射类

using UnityEngine;

public class BulletShooting : MonoBehaviour {

    float times;
    float speed;
    float Horizontal;
    float Vertical;
    // Use this for initialization
    void Start () {
        times = 0;
        speed = 10f;
    }
    
    // Update is called once per frame
    void Update () {
        Horizontal = Input.GetAxis("Horizontal");
        Vertical = Input.GetAxis("Vertical");
        transform.Translate(Horizontal*Time.deltaTime* speed * -1, Vertical * Time.deltaTime * speed,0);
        
        if (Input.GetKey(KeyCode.J)&& Time.time>times)
        {
            times = Time.time+0.2f;
            GameObject bullet = BulletManage.Get().GetBullet();
            bullet.SetActive(true);
            bullet.GetComponent<BulletObject>().ShootBullet(transform.position,new Vector3(0,0,-1000f));
        }

    }
}

子弹类

using UnityEngine;

public class BulletObject : MonoBehaviour {

    
    public void ShootBullet(Vector3 pos, Vector3 force)
    {
        gameObject.transform.position = pos;
        gameObject.GetComponent<Rigidbody>().AddForce(force,ForceMode.Force);
        Invoke("HideBullet", 5f);
    }

    void HideBullet()
    {
        gameObject.SetActive(false);
    }

}

猜你喜欢

转载自blog.csdn.net/tran119/article/details/81173273
今日推荐