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));
more ▼

asked Jun 12, 2011 at 01:43 AM

avatar image

16 10 9 11

Remember, you can format code by using the button with 0s and 1s on it.

Jun 13, 2011 at 11:28 AM Herman Tulleken

Ok was wondering how i did that - thanks

Jun 13, 2011 at 08:42 PM jammerjar
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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;
 function checkhit(){
     if(hit == 5){
more ▼

answered Jun 12, 2011 at 02:27 AM

avatar image

Eli Davis
263 35 29 33

Hey Eli thought I would just let you know that that worked great thanks. Applied it as a separate script instead 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

Jun 13, 2011 at 09:07 AM jammerjar

@jammerjar if Eli's solution fixed your problem, please accept it as the answer to your question.

Jun 13, 2011 at 03:47 PM Chris D
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments



asked: Jun 12, 2011 at 01:43 AM

Seen: 2354 times

Last Updated: Jun 13, 2011 at 08:42 PM