- Home /
Destroy object after 5 collisions
Hi this is my first post so go easy on me. I have searched but cant find info on a way to count the number of hits an object receives and and destroy it after it has been hit say 5 time.
My guess is that I need to count the number of collisions in a variable and then when the variable = 5 destroy object. But I can figure out how to do that. Oh yes and the object to destroy is an instance.
I have been trying to adapt this script that destroys after a period of time but no joy so thought i would put my hand up.
// Instantiate a rigidbody then set the velocity
var projectile : Rigidbody;
var destroyTimeMin = 2.0;
var destroyTimeMax = 5.0;
var pop : ParticleEmitter;
function OnCollisionEnter (col : Collision) {
Instantiate(pop, transform.position, transform.rotation);
}
function Update () {
// Ctrl was pressed, launch a projectile
if (Input.GetButtonDown("Fire1")) {
// Instantiate the projectile at the position and rotation of this transform
var clone : Rigidbody;
clone = Instantiate(projectile, transform.position, transform.rotation);
// Give the cloned object an initial velocity along the current
// object's Z axis
clone.velocity = transform.TransformDirection (Vector3.forward * 10);
Destroy(clone.gameObject, Random.Range(destroyTimeMin, destroyTimeMax));
}
}
Remember, you can format code by using the button with 0s and 1s on it.
Answer by Eli-Davis · Jun 12, 2011 at 02:27 AM
for seeing if the object is getting hit 5 times I'd think you'd simple do this...
var hit = 0;
function OnCollisionEnter(){
hit +=1;
checkhit();
}
function checkhit(){
if(hit == 5){
Destroy(gameObject);
}
}
Hey Eli thought I would just let you know that that worked great thanks. Applied it as a separate script ins$$anonymous$$d of making it part of my instantiate script. It didnt like having two OnCollisionEnters and I couldnt make it work inside the existing function. Not sure if that's a bad thing to do but it work. Thanks
@jammerjar if Eli's solution fixed your problem, please accept it as the answer to your question.