- Home /
OnCollisionEnter not working for bullet
HI all,
I have created an object that fires some bullets from a tutorial but I can figure out why the OnCollisionEnter event isn't firing when the bullet object hits a wall, I just want to destroy the bullet when it hits the wall. This is the bullet class that I have applied to an empty object which has a prefab linked to it. public class Bullet : MonoBehaviour {
public float moveSpeed = 40f;
public Rigidbody projectile;
public Rigidbody clone;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if (Input.GetKey (KeyCode.Space))
Shoot ();
}
void Shoot()
{
clone = (Rigidbody)Instantiate (projectile, transform.position, transform.rotation);
clone.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
clone.detectCollisions = true;
clone.velocity = transform.TransformDirection(new Vector3(0,0,moveSpeed));
Destroy (clone.gameObject,3);
}
void OnCollisionEnter(Collision collision)
{
Destroy (clone.gameObject);
}
The bullets shoot ok and stop when they hit the wall but even when debugging the OnCollisionEnter method isn't called.
Any help would be great. Thanks, Anto
If your debug shows OnCollision is not called then perhaps your Wall does not meet the requirements for a collision?
The wall has the BoxCollider on it by default and all of the bullets do actually stop when they hit the wall but for whatever reason the method isn't called. I was thinking it is because the OnCollisionEnter is a member method of Bullet but I'm not actually creating an instance of the Bullet class, I'm creating a variable and assigning a prefab to it. I don't fully understand how Unity handles the scripts being applied to an object so maybe I'm not thinking about it in the right way.
Answer by Philtermango · Apr 06, 2014 at 09:13 AM
The OnCollisionEnter will only be called on scripts that are attached to the wall or bullet. The script you posted is not attached to either so OnCollisionEnter is not called. That Bullet script just instantiates the bullet and sends it on its way. Add OnCollisionEnter to a script attached to the bullet prefab or wall and it should work.
Answer by QuantumMacgyver · Apr 06, 2014 at 04:39 AM
If the bullets are moving fast enough, they can sometimes pass entirely though the wall in between physics updates. (Slow them waay down and see if the problem's still there. If it is, ignore the rest of this post.)
Assuming that fixed it, all you need to do is have your bullets raycast ahead of themselves and run your destroy script when they either hit the target or would hit it by the next frame.
Thanks for the reply Quantum$$anonymous$$acgyver, but the bullets are already moving very slowly, every bullet hits the wall and stops correctly but the OnCollisionEnter method above isn't called when the bullet hits the wall. I'll look into the raycasting for the bullets, was just trying to keep it simple for a intro to Unity.