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;

}

1 Answer

1

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 <= 0){ // if endTime ended, suicide object
            Destroy(gameObject);
        }
    }
}

You can call Activate in OnMouseDown, if you want to consider the time the button is held down, but only call it in OnMouseEnter if the object must be destroyed even without a click. Calling Stop at OnMouseExit and OnMouseUp is ok, since this last event only occurs if the mouse up while over the object.