Taking down trees in game

I wanted to make this lumberjack game where you take down trees with your axe and it will then replace the trees with lumber (I know, that game would suck but it’s for educational purposes). So I began to write the script and all that but it only replace the tree with the lumber in the begining and the health(health of the tree) does not work. It would be nice if someone helped (sorry for my english). :slight_smile:

The script:

var myHealth : int = 60;
var Damage : int = 20;
var myTrunck : GameObject;
var myTree : GameObject;
 
 
function OnCollisionEnter (){

      
      myHealth -= Damage;
   
} 

function Update ()
{
    if(myHealth > 0)
    {
       var clone = Instantiate(myTrunck, transform.position, transform.rotation);
       GameObject.Destroy(myTree);   
    }
}

Set a Sphere collider around your tree, set it to trigger and you could use:

var isCutting:bool = false;
function OnTriggerEnter(col:Collider){
    isCutting = true;
}
function OnTriggerExit(col:Collider){
    isCutting = false;
}

function Update(){
    if(isCutting) health -= damage * Time.deltaTime;
    if(health <= 0){
        Instantiate(myTrunck, myTree.position, Quaternion.identity);
        Destroy(myTree);
    }
}

You also need all other variables obviously.
Your issue was that OnCollisionEnter only returns true when entering, that is once only or you would to go back and forth constantly. Using a trigger box bigger that the tree, you can tweak your boolean and make things happen.

If you leave the trigger collider, you stop cutting the tree.