Still learning and trying to make a tree chopping script.

Ive made a raycast script from a youtube video i watched, the only problem with it is that it doesnt want to take health away from the tree. I made sure the tree had a “tree” tag and the axe i have is linked to it.
If you wouldnt mind taking some of your time and help me out a little. Thanks!

public class AxeRaycast : MonoBehaviour
{
//Variables
public GameObject axe;
private bool isEquiped = false;

private void Update()
{
    if(!axe.activeSelf && Input.GetKeyDown(KeyCode.Alpha1))
    {
        isEquiped = true;
        axe.SetActive(true);
    }
    else if(Input.GetKeyDown(KeyCode.Alpha1))
    {
        isEquiped = false;
        axe.SetActive(false);
    }
     //Raycast
    Vector3 fwd = transform.TransformDirection(Vector3.forward);
    RaycastHit hit;

    //Origin, Direction, RaycastHit, Length
    if(Physics.Raycast(transform.position, fwd, out hit, 10))
    {
        if(hit.collider.tag == "tree" && Input.GetMouseButtonDown(0) && isEquiped == true)
        {
            Tree treeScript = hit.collider.gameObject.GetComponent<Tree>();
            treeScript.treeHealth--;
        }
    }
}

The tree tag needs to be spelled exactly “tree”, capitalization and all. Also, make sure that the tree has a collider attached that is not set to trigger (it could be a trigger instead, but you’d have to add another parameter to the raycast to indicate that triggers are acceptable). The tree must also not be on the IgnoreRaycast layer.

Try adding Debug.Logs to this at some points- put one just inside of the raycast conditional first (right before “if(hit.collider.tag…”, and then if that’s printing to the console while aiming at the tree, put it right AFTER the “if(hit.collider.tag…” line instead, and test if it’s printing to the console when you try clicking the tree.

I just tried your suggestions, first the tag is correct and it is not on the IgnoreRaycast layer. But, i tried the Debug.Log before my if(hit.collider statement and it would give a log every frame. Also, I tried the Debug.Log after the statement and it would start to take health away from the tree without clicking. Its strange and im not sure what im doing wrong. Any suggestions?

As well as when i would ‘Unequip’ my axe it would still chop the tree down.