I'm a beginner developer and I'm trying to make a 2D survival type game where you have to break a trees. I'm using a raycast to detect when you click a tree. When I run the program, it says "Object reference not set to an instance of an object". Usually you just have to declare a public variable, but all variables are set. Never seen this before. Here's what I have:
if (Input.GetMouseButtonDown(0))
{
Debug.DrawRay(transform.position, mousePosition * 0.1f, Color.red);
RaycastHit2D hit = Physics2D.Raycast(playerRb.transform.position, mousePosition, 0.1f);
if (hit.collider != null)
{
hit.transform.GetComponent<TreeScript>().treeHealth -= 1;
}
}
I've pinpointed the problem to be on the last line. I have a script called TreeScript and a variable there for the treeHealth.