Null reference exception, even though I want my method to return null
Hi there,
I'm relatively new to C# and Unity, so I suspect the issue I'm having is that my fundamental approach is wrong. But I can't work out exactly how.
I'm working on an interaction system that uses a Raycast to determine if an item in front of a player can be interacted with. The code looks like this:
private void InteractAction()
{
GameObject hitInteractable = InteractionCheck();
if (hitInteractable.GetComponent<IInteractable>() != null)
{
hitInteractable.GetComponent<IInteractable>().Interact();
}
else
{
Debug.Log("You can't interact with this");
}
}
//Fires a ray forward to check if an item can be interacted with, returns hit game object
private GameObject InteractionCheck()
{
RaycastHit2D hit = Physics2D.Raycast(faceDirection.transform.position, Vector2.up, interactionDistance);
if (hit == true)
{
return hit.collider.gameObject;
}
else
{
return null;
}
}
Now, I only want to run InteractAction() if the Raycast hits something, so I've set the Raycast up so that it returns null if it hits nothing - this is what's giving me the Null Reference Exception (I think). So the obvious solution would be to return a GameObject and that'd be problem solved, but I don't want any GameObject passed into InteractAction() if it can't be interacted with. Can anyone shine some light on what I've missed? Could I just pass a dummy object that doesn't have so no code would ever run? Feels very hacky. I should say, I use the InteractionCheck() method in a few instances, hence why I've seperated them out as I have... but maybe that's the wrong approach.
Thanks in advance!
Your answer
Follow this Question
Related Questions
Multiple game objects same script 0 Answers
How is this Instantiate NullReferenceException? 0 Answers
Raycast2D don't hit anything below 0 Answers
Finding unique interacting function within gameObject 0 Answers
NullReferenceException when attempting to call a GameObject from within PointerEventData 1 Answer