- Home /
Shooting using an object pool
This is actually my first time posting a question in Unity Answers so if this question has already been asked please excuse me.
Today I am working on a gun that shoots at center screen and uses an object pool, this should be pretty simple but for whatever reason I am having some issues. I have a script on the player called Gun.CS when it uses instantiation the bullets trajectory is perfect but when I incorporate the object pool the bullets do not shoot correctly anymore. Any help would be greatly appreciated!''
// Update is called once per frame
void Update ()
{
Aim();
if (Input.GetButtonDown ("Fire2") && Time.time > nextFireTime && currAmmo > 0)
{
Shoot();
}
}
void Shoot()
{
print("firing");
audio.PlayOneShot(impact, volume);
//This is how I would like to fire my bullets, but they fly in different directions
Rigidbody cloneRb = GenericObjectPool.current.GetPooledObject("BulletBlue").GetComponent<Rigidbody>();
cloneRb.gameObject.SetActive(true);
cloneRb.gameObject.transform.position = firePoint.position;
cloneRb.gameObject.transform.rotation = firePoint.rotation;
//This currently does work but I do not want to create and destroy bullets as this will probably be a mobile game
//GameObject go = Instantiate (projectile, firePoint.position, firePoint.rotation);// as Rigidbody;
//go.GetComponent<Rigidbody>().AddForce(firePoint.transform.forward * projectileForce);
currAmmo -= 1;
nextFireTime = Time.time + fireRate;
}
void Aim()
{
float screenX = Screen.width / 2;
float screenY = Screen.height / 2;
RaycastHit hit;
ray = cam.ScreenPointToRay(new Vector3(screenX,screenY));
if (Physics.Raycast(ray, out hit))
{
firePoint.LookAt(hit.point);
}
}
3 questions and 1 lead:
- Why do you set the Rigidbody active and not the whole gameObject ?
- Also why is //go.GetComponent().AddForce(firePoint.transform.forward * projectileForce); commented ?
- Finally, what do you mean with "do not shoot correctly" ?
$$anonymous$$aybe you could try setting the rigidbody variables to 0 when you take your object out of the pool ? (like the velocity)
Hi, Though the bullet gameobject gets deactivated by pool manager, its velocity wont get reset. So I think once the bullet gameobject gets deactivated, you need to reset its velocity for next launch.
//Attach this script to the bullet prefab
public class Bullet : $$anonymous$$onoBehaviour
{
//Function will be called when this gameobject gets deactivated
void OnDisable()
{
//Reset the velocity of the rigidbody component
gameObject.GetComponent<Rigidbody>().velocity = Vector3.zero;
}
}