- Home /
Objects do not destroy on Collision
Hello, I recently made a script to destroy objects when the collide with bullets but the object does not destroy and instead bounces off the object. I do not know what the exact problem is because I have the bullet prefab and explosion prefab made already. Can someone please help me know why objects are not being destroyed after they are hit by a bullet?
Here is my code for the bullet:
var speed : float = 30;
var explosion : GameObject;
function Start () {
Invoke("Destroy_Bullet", 1.0);
}
function Update () {
transform.Translate (Vector3.forward * speed * Time.deltaTime);
}
function OnTriggerEnter (other : Collider) {
if (other.gameObject.tag == "shooter") {
Instantiate (explosion, transform.position, transform.rotation);
Destroy(gameObject);
}
}
function Destroy_Bullet () {
Destroy(gameObject);
}
Code for the enemy:
function OnTriggerEnter(other: Collider){
Destroy(other.gameObject);
}
Well in the code for the enemy, it looks like you are destroying the game object whose collider entered the trigger. So if the collider of the enemy is set as a trigger, the "gameObject" whose collider entered the trigger is the bullet. So you are actually trying to destroy the bullet.Not the enemy.
Also, in your bullet OnTriggerEnter(), you are calling Destroy(gameObject), which will destroy the bullet. You want to use Destroy(other.gameObject) ins$$anonymous$$d.
Answer by Gizmoi · Jan 28, 2013 at 01:10 AM
If the objects bounce off each other that would suggest that they are not triggers i.e. they do not have isTrigger checked. OnTriggerEnter only worked when one or more of the objects have a Collider that is a trigger. I think you want to use OnCollisionEnter rather than OnTriggerEnter.
Edit: a good way to check is place some Debug.Log calls in the function and see if they trigger.