I am working on a game in Unity where you can interact with chests. To make this work I use the camera to detect if the player is looking at the chest or not. But i keep getting the following error:
NullReferenceException: Object reference not set to an instance of an object
PlayerInteraction.Update () (at Assets/cs scripts/PlayerInteraction.cs:22)
Here is the code I use for this:
public Camera cam;
void Start()
{
cam = Camera.main;
}
void Update()
{
Ray ray = cam.ScreenPointToRay(new Vector3(Screen.width / 2f, Screen.height / 2f, 0f));
RaycastHit hit;
}
I tried changing public Camera cam;
to Camera cam;
but this didn't seem to change anything. I also checked if the Unity side of things here is correct but there are no issues there either.
What should i do to fix this?
Thanks a lot!