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. :/
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);
}
}
Answer by doublemax · Sep 26, 2016 at 07:26 AM
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.
Answer by FlyingFlambe · Sep 26, 2016 at 07:26 PM
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.
As always, you should program defensively.
hit.collider.gameObject.GetComponent<HexPlateController>().move
You're assu$$anonymous$$g that "hit.collider.gameObject.GetComponent()" returns something valid and call its method. But what if it returns null?
If a gameobject with tag "HexPlate" should always have such a component, there must be an error somewhere else. Use Debug.Log to print 'hit.collider.gameObject.name' and check if it's the object you're excepting and if it really has a component "HexPlateController".