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.
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;
GameObject objCreatedBullet = (GameObject)Instantiate(scriptVariable.objBullet, tempVector, Quaternion.LookRotation(inputRotation)); // create a bullet, and rotate it based on the vector inputRotation
And this is the movement code for the bullet, very basic.
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
Dec 26 '11 at 02:47 AM