1

I have a simple object pool in place for a gun I am using. However after an object has been set to inactive and is free for use again, when it gets used it shoots out in its old direction. I am not used to using pooling for such tasks so I'm not sure exactly why it is happening.

void Start () 
{
    bullets = new List<GameObject> ();
    for (int i = 0; i < amountOfBullets; i++) 
    {
        GameObject obj = (GameObject)Instantiate(bullet);
        obj.SetActive(false);
        bullets.Add(obj);
    }
}

// Update is called once per frame
void Update () 
{
    if (Input.GetKeyDown (KeyCode.Mouse0)) 
    {
        Shot ();
        anim.Play("Recoil", -1 , 0);
    }
    if (Input.GetKeyUp (KeyCode.Mouse0)) 
    {
        anim.StopPlayback();
        stuff.Stop();
    }
}

public void Shot()
{
    for (int i = 0; i < bullets.Count; i++) 
    {
        if(!bullets[i].activeInHierarchy)
        {
            bullets[i].transform.position = bulletSpawn.transform.position;
            bullets[i].transform.rotation = bulletSpawn.transform.rotation;
            bullets[i].SetActive(true);
            break;
        }
    }

    buttonPressed = true;
    audio.PlayOneShot (shot);
    stuff.Play ();
}

The bullet spawn is an empty game object that is attached to the gun. Also the bullets are set inactive via a script on the prefab which sets them to inactive after 2 seconds.

James Webster
  • 31,873
  • 11
  • 70
  • 114
bSky
  • 187
  • 2
  • 12

0 Answers0