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
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");
}
}