- Home /
Destroy On Collision
simple question, how would I go about writing a script that would destroy a gameobject (enemy) when a bullet prefab collides with it?
Answer by TheFrankman123 · Oct 12, 2011 at 09:23 PM
Along the lines of
function OnCollisionEnter(myCol: Collision){
if(myCol.gameObject.name == "enemy"){
Destroy(myCol.gameObject);
}
Alternitively you can make it check if it's collided with an item with a tag of enemy.
Answer by chemicalvamp · Oct 13, 2011 at 10:33 AM
using System.Collections.Generic;
List<Collider> colliders = new List<Collider>();
void OnCollisionEnter(Collision collision)
{
if (collision.collider.gameObject.tag = "Enemy")
{
colliders.Add(collision.collider); // saves the enemy for later respawn
collision.collider.gameObject.active = false; // deactivate instead of destroy so you could later reactivate (respawn) him
}
}
Answer by roamcel · Oct 13, 2011 at 10:14 AM
Depending on the complexity of your needs you can opt for collision and trigger. For example if you intend to fully model a physical projectile, then you are usually better off with Collision, rigidbodies etc., but in those cases you need to fine-tune the physics min collision for penalty parameter, otherwise very fast objects like projectiles will seem to 'miss' the things they contact with. The trigger approach is far easier to implement, but sacrifices realism for ease of implementation.
Be sure to check the guide for rigidbodies and colliders to fully understand the benefits of OnTriggerEnter and OnCollisionEnter
Answer by umangindianic · Jul 02, 2013 at 09:28 AM
void OnCollisionEnter(Collision collision){
if(collision.gameObject.name == "enemy"){
Destroy(this.gameObject);
}
}
You can use collision.gameObject.tag instead of use of name.
Its not working :( void OnCollisionEnter(Collision collision){ if(collision.gameObject.name == "enemy"){ Destroy(this.gameObject); } } It says that "a namespace can only contain types and namespace Decleraions