Why do I get a Null Reference error?

Hey! I am using variables from another script and it gives me Null Reference errors. The error appears as soon as the tree should normally fall (after chopping the tree 4 times), so in ‘void BreakTree’. The function is actually called (I debugged that). I can’t figure out why… can anybody help me with this? Don’t laugh at my bad coding skills please :slight_smile:


This is the script where the error is (in ‘void BreakTree’):


public class TreeHealth : MonoBehaviour
{
    public int health = 100;
    public TreeChopping choppingScript;

    void Update()
    {
        if (health <= 0)
        {
            BreakTree();
        }
    }

    void BreakTree()
    {
        Debug.Log("Tree Breaks");
        // Adds a rigidbody to the upper part of the tree & falls down
        Rigidbody rb = choppingScript.treeTarget.AddComponent<Rigidbody>();
    }
}

This is the script where the variable is from:


public class TreeChopping : MonoBehaviour
{
    public GameObject player;

    // Axe related code
    public bool axeEquipped = false;
    private float hitRange = 3f;

    // Tree
    public GameObject treeTarget;
   
    // Tree HP
    private int damagePerHit = 25;
    public TreeHealth healthScript;

    void Update()
    {
        // Equip axe
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            Debug.Log("Axe equipped");
            axeEquipped = true;
        }

        var ray = Camera.main.ScreenPointToRay(new Vector2(Screen.width / 2, Screen.height / 2));

        if (Input.GetKeyDown(KeyCode.Mouse0) && axeEquipped)
        {
            if (Physics.Raycast(ray, out var hitInfo, hitRange))
            {
                if (hitInfo.collider.CompareTag("Tree"))
                {
                    var treeHealth = hitInfo.collider.GetComponentInParent<TreeHealth>();
                    treeTarget = hitInfo.collider.gameObject;
                    if(treeHealth)
                    {
                        DamageTree(treeHealth);
                    }
                }
            }
        }
    }

    void DamageTree(TreeHealth treeHealth)
    {
        // Tree loses HP
        treeHealth.health -= damagePerHit;
        Debug.Log("Tree damage");
    }
}

Maybe the choppingScript you have assigned to the TreeHealth have a null treeTarget and isn’t the same as that you set in TreeChopping.

Try

Debug.Log("treeTarget null: " + treeTarget==null);

I would suggest you restructure your code to operate on objects. Player and Tree. The Player script goes to all player objects, and the Tree script on all the trees. It’s almost the same as you have now, but you could make it so that the player is aware of the tree, and can chop it when collision is detected. But the tree does not need to have a reference to the player.