Why won't this destroy code work?

I am new to unity and scripting. I wanna learn how to destroy a cube in my game when i click on it. I wrote the following script in js and named it destroy food.

#pragma strict
function Start () {

}

function Update () {
   if (Input.GetMouseButtonDown);
   {
      Destroy(gameObject);
   }

}

I assigned it to the cube i wanted to destroy, but when i hit the play button it gave me the following error.

Assets/destroy food.js(9,28): BCE0044: expecting :, found ‘;’.

What am i doing wrong?

Looking at your code a little closer, you have a syntax error with if(Input.GetMouseButtonDown); should be: if(Input.GetMouseButtonDown(0)) { Destroy(gameObject); } But that is just to fix your compile error. This won't do what you want since it only detects if the mouse button is clicked, not if you clicked the object itself. See my below answer to do that...

2 Answers

2

You have a semicolon after your if statement.

Make it

function Update () { 
if (Input.GetMouseButtonDown) { 
Destroy(gameObject); }

}

Hard to read your code without it being formatted to help determine your compile error. But try the following to do what you want.

function OnMouseOver()
{
   if(Input.GetMouseButtonDown(0))
   {
      Destroy(gameObject);
   }
}