Simple ObjectPool with bullets

如果在游戏中需要大量的创建和销毁物体,那么最好是引入对象池。

 

一下是一个简单的例子:

创建一个对象bullet

 

把bullletDestroy Bullet添加到Bullet对象上。生成一个bullet的prefab。

public class BulletUpdate : MonoBehaviour {

    public float Speed = 5f;

    /// <summary>
    /// Translate the bullet every frame
    /// </summary>
    public void Update()
    {
        transform.Translate(0, Time.deltaTime * Speed, 0);
    }
}

  

public class BulletDestroy : MonoBehaviour {

    /// <summary>
    /// Invoke Destroy
    /// </summary>
    public void OnEnable()
    {
        //            throw new System.NotImplementedException();
        //            Destroy(gameobject, 2f);
        Invoke("Destroy", 2f);
    }

    public void Destroy()
    {
        //            throw new System.NotImplementedException();
        gameObject.SetActive(false);
    }

    public void OnDisable()
    {
        //            throw new System.NotImplementedException();
        CancelInvoke();
    }
}

  

public class BulletFire : MonoBehaviour {


    public float FireTime=0.05f;

    public GameObject Bullet;
    private int PoolAmount = 20;
    private List<GameObject> Bullets;
   

    /// <summary>
    /// Fire the bullet erery FireTime
    /// </summary>
    public void Start()
    {
        //            throw new System.NotImplementedException();
        Bullets = new List<GameObject>();
        for (int i = 0; i < PoolAmount; i++)
        {
            GameObject obj = Instantiate(Bullet) as GameObject;
            obj.SetActive(false);
            Bullets.Add(obj);
        }
        InvokeRepeating("Fire", FireTime, FireTime);
    }

    /// <summary>
    /// Reset the Bullets's bullet that contains position, rotatin, acitve.
    /// </summary>
    public void Fire()
    {
        //            throw new System.NotImplementedException();
        //            Instantiate(Bullet, transform.position, Quaternion, identify);
        for (int i = 0; i < Bullets.Count; i++)
        {
            if (!Bullets[i].activeInHierarchy)
            {
                Bullets[i].transform.position = transform.position;
                Bullets[i].transform.rotation = transform.rotation;
                Bullets[i].SetActive(true);
                break;
            }
        }
    }
}

  把bulletfire添加到一个空对象上。 在对象中引用bulletprefab。

 

值得思考的地方。

在invokerepeating的调用下,每隔一段时间就调用Fire。 调用一次,就激活一个对象,再退出。

 

posted @ 2014-07-13 10:36  penney  阅读(330)  评论(0)    收藏  举报