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;
}
}
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
Agreed.. with what this dude said
– dreg_master