Why am I getting an object reference error?

Viewed 10

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.

1 Answers

I found what my problem was. I used "if (hit.collider != null)" and then attempted to modify a specific component. I believe the raycast was hitting other objects and failing to transform it because it didn't have the treeScript component. I just added an if statement to detect if the object I hit is a tree.

Related