- Home /
Destroy A Game Object After Mouse is held for a certain amount of time
What I want to happen is for a game object to be destroyed after 5 seconds only if the mouse is over the object and is held. Here is my script, which just doesn't seem to work.
var wasClicked : boolean;
var endTime : float;
var timeLeft : int;
function OnMouseDown() {
wasClicked = true;
Activate();
}
function OnMouseUp() {
wasClicked = false;
Stop();
}
function OnMouseEnter() {
if (wasClicked) {
Activate();
}
}
function OnMouseExit() {
Stop();
}
function Activate() {
endTime = Time.time + 5.0;
timeLeft = endTime - Time.time;
if (timeLeft < 0)
{
Destroy(gameObject);
}
}
function Stop() {
endTime = 5.0;
}
Comment
Answer by aldonaletto · Oct 01, 2011 at 07:37 PM
OnMouseEnter and OnMouseDown only occur once, so Activate isn't checking the endTime. You should check endTime in Update:
var endTime: float = 0;
function Activate(); endTime = 5; }
function Stop(){ endTime = 0; }
function Update(){ if (endTime > 0){ // only check timer if > 0 // subtract the time elapsed since last update endTime -= Time.deltaTime; if (endTime
Your answer
![](https://koobas.hobune.stream/wayback/20220612232742im_/https://answers.unity.com/themes/thub/images/avi.jpg)