Search code examples
mobileunity-game-engineunityscript

Destroy object with boolean control


I found a tap on object in unity tutorial and tried to add some code for destroy object.

My problem is when I try to tap counter decrease and boolean change false. but if I continue tap on object , enemy still destroy

How can I correct the code?

var counter : int =3;
public var destroy = true;
function Update () {
    var hit: RaycastHit;
   var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
   if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)    

    {
       if (Physics.Raycast (ray, hit, 100)) 
      {
           if(hit.collider.gameObject.tag == "weapon" && destroy==true)

                counter-=1;
                DestroyEnemy();
                Check();
                                  }
        }
    }

function DestroyEnemy() {

 Destroy(GameObject.Find("enemy2(Clone)"));
 Destroy(GameObject.Find("enemy(Clone)"));

}

function Check() {

if (counter <=0)
destroy=false;

}

Solution

  • You're probably missing the parentheses in your if statement:

    if(hit.collider.gameObject.tag == "weapon" && destroy==true)
        counter-=1;
        DestroyEnemy();
        Check();
    

    If you run this, only counter -= 1 will be inside the if statement. DestroyEnemy() and Check() will be run each time you tap regardless of the destroy value. Give parentheses for multi line if statement:

    if(hit.collider.gameObject.tag == "weapon" && destroy==true)
    { // this
        counter-=1;
        DestroyEnemy();
        Check();
    } // and this