Destroy onCollisionStay for seconds

I'm trying to program a script that will destroy a physical object if it stays in touch with an object for more than a few seconds. So far, the script has two major problems:

A.) It won't add using Time.deltaTime, so I can't fill a counter B.) When the function is triggered, it destorys all objects with the code attached to it, not the specific object. Like instead of destroying the one wall out of four, it destroys all of them.

Can anyone help?

//What's the current build up?
static var Touched: int = 0;
//How much do we build up by?
var DC: float = 1.0;
//Are we Touching?
var Touching: boolean = false;

function Update (){

if(Touching){
Touched += DC * Time.deltaTime;
}
if(Touched >= 100){
Destroy(gameObject);
    }

}

function OnCollisionStay(collision:Collision){
if(collision.gameObject.CompareTag("Gatherer")){
    Touching = true;
    }
    else{
    Touching = false;
    }

}

Agreed.. with what this dude said

2 Answers

2

From the reference: "OnCollisionStay is called once per frame for every collider/rigidbody that is touching rigidbody/collider."

So your script could be much simpler and look something like this (untested):

var Touched: float = 0.0; //changed to float
var DC: float = 1.0;

function OnCollisionStay (collision:Collision) {
  if(collision.gameObject.CompareTag("Gatherer")) {
    Touched += DC * Time.deltaTime;
  }
  if (Touched >= 100) {
    Destroy(gameObject);
  }
}

Maybe you have to reset "Touched" for every new collision using OnCollisionEnter().

Still doesn't work

Do you want to be able to reset the counter if the object leaves? If not you could probably use efges solution. If you want it to be reset then you should probably use OnCollisionEnter to mark a flag and store all collided objects in a collection, and remove them in OnCollisionLeave. If there is no more objects in your collection, you could reset.

If you want this to execute 100ms after any one touch and then kill everything that collides you could start the counter in OnCollisionEnter and then never reset this. When the time is out you could then call OverlapSphere to find all objects inside the area and destroy them in Update

http://unity3d.com/support/documentation/ScriptReference/Physics.OverlapSphere.html

I need it to hold for 100 seconds.