I am working on a top down shooter, just recently I changed my code to recycle a group a prefabs rather then create and destroy them over and over again. The group of gameObjects is contained in List. When I made the change the bullets starting moving in erratic directions instead of strait. I have no idea why this little change would have caused this problem unless there was something jacked in the movement code. I would be great if someone could take a look at my code and see if anything pops out.
This is the code to instantiate or reuse game objects.
void HandleBullets()
{
bulletsLeft -= 1;
tempVector = Quaternion.AngleAxis(8f, Vector3.up) * inputRotation;
tempVector = (transform.position + (tempVector.normalized * 0.8f));
var bullet = Bullets.Find(b => !b.active);
if (bullet != null)
{
bullet.transform.position = tempVector;
bullet.transform.rotation = Quaternion.LookRotation(inputRotation);
bullet.active = true;
}
else
{
GameObject objCreatedBullet = (GameObject)Instantiate(scriptVariable.objBullet, tempVector, Quaternion.LookRotation(inputRotation)); // create a bullet, and rotate it based on the vector inputRotation
Physics.IgnoreCollision(objCreatedBullet.collider, collider);
Bullets.Add(objCreatedBullet);
}
}
And this is the movement code for the bullet, very basic.
void Update()
{
if (gameObject.active)
{
timeSpentAlive += Time.deltaTime;
if (timeSpentAlive > 2) // if we have been travelling for more than one second remove the bullet
{
gameObject.active = false;
}
// move the bullet
transform.Translate(0, 0, moveSpeed * Time.deltaTime);
transform.position = new Vector3(transform.position.x, 0, transform.position.z); // because the bullet has a rigid body we don't want it moving off it's Y axis
}
}