How do I fix a Null Reference Exception (object reference not set to an instance of an object)?

The error continues to show up and I’m not really understanding why. :confused:

The error appears on the line “if (hit.collider.tag == …” as well as on the line “hit.collider.gameObject.GetComponent().move = new Vector2(…)”. The error seems to occur a lot, and the game still runs (albeit broken) even when the errors appear. What’s going on?

Thank you in advance.

    public void HpmStandardUp()
    {
        RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
        GameObject hexPlateGameObject = GameObject.FindGameObjectWithTag("HexPlate");

        if (hit.collider.tag == "HexPlate" && (hit.collider != null))
        {
            hpmTimer += Time.deltaTime;
            CalculateHexPlateAcceleration();
            hexPlateVelocity += hexPlateAcceleration * Time.deltaTime;

            HexPlateController hexPlateController = hexPlateGameObject.GetComponent<HexPlateController>();
            hit.collider.gameObject.GetComponent<HexPlateController>().move = new Vector2(0, hexPlateNormalSpeed.y + hexPlateVelocity + hpmStandard + Mathf.Pow(hpmTimer, hpmPower));
            print("Hex Plate Velocity: " + hexPlateVelocity);
        }
        else
        {
            hpmTimer = 0;
            //CalculateHexPlateVelocity();
            //print("Hex Plate Velocity: " + hexPlateVelocity);
            //GetComponent<HexPlateController>().move = new Vector2(0, hexPlateNormalSpeed.y);
        }
    }

if (hit.collider.tag == “HexPlate” && (hit.collider != null))

Change to:

if ( hit.collider != null && hit.collider.tag == "HexPlate")

You should check the collider for null before you use it.

Thanks for the solution and reasoning, @doublemax. Still having the issue with the second line though. If it helps, the script listed above is on the player, but the HexPlateController component is on the object being moved.