I’ve created a pool of projectiles controlled by physics that I keep track of in a static Dictionary<GameObject, bool> stored in the class for the objects that fire the projectiles so that when something needs one of these objects, it can check the pool to see if any of the projectiles have been recaptured and respawn them at their own position. But any time I have more than two firing objects, if I try to reuse a projectile, it will move to the firing location and then between LateUpdate and the next FixedUpdate, it will move back to its original location.
Relevant pool-usage code below. Please let me know if you think you need more information.
public class Shooter : GridItem, CanBeHitByLaser
{
private static System.Collections.Generic.Dictionary<GameObject, bool> liveProjectiles = new System.Collections.Generic.Dictionary<GameObject, bool> ();
public GameObject projectilePrefab;
public void OnLaserHit (LaserHitParams laserHitParams)
{
foreach (GameObject liveProjectile in liveProjectiles.Keys)
{
if (!liveProjectiles[liveProjectile])
{
//There is a projectile available in the pool.
FireProjectile (liveProjectile, laserHitParams);
return;
}
}
//No live projectiles available, must create one.
GameObject instantiatedProjectile = (GameObject)GameObject.Instantiate (projectilePrefab, transform.position, Quaternion.identity);
liveProjectiles.Add (instantiatedProjectile, true);
FireProjectile (instantiatedProjectile, laserHitParams);
}
private void FireProjectile (GameObject projectileToFire, LaserHitParams laserHitParams)
{
projectileToFire.SetActiveRecursively (true);
projectileToFire.rigidbody.WakeUp ();
projectileToFire.rigidbody.velocity = Vector3.zero;
liveProjectiles[projectileToFire] = true;
projectileToFire.transform.position = transform.position;
projectileToFire.SendMessage ("OnLaserHit", laserHitParams, SendMessageOptions.DontRequireReceiver);
}
private void CaptureProjectile (GameObject projectile)
{
if (liveProjectiles.ContainsKey (projectile))
{
projectile.rigidbody.velocity = Vector3.zero;
projectile.transform.position = Vector3.zero;
projectile.rigidbody.position = Vector3.zero;
projectile.SetActiveRecursively (false);
liveProjectiles[projectile] = false;
}
else
{
GameObject.Destroy (projectile);
}
}
}
Video of the effect I’m seeing can be found here. If anyone’s seen something like this or has an explanation of what I can do to properly reset a rigidbody when deactivating its GameObject, please let me know.