0

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!

101
  • 19
  • 6
  • The cam object is not connected to a a camera. Check your startup files to see if you are really making a connection to unity. – jdweng Jan 20 '22 at 15:42
  • 1
    Make sure there is a `Camera` in your scene that is tagged `MainCamera` .. otherwise `Camera.main` won't find anything – derHugo Jan 20 '22 at 16:41
  • @jdweng what startup files? connected to unity? – Ruzihm Jan 20 '22 at 17:02
  • Usually it either the proj or the config file. Sometimes it just may be hard coded in the cs file(s). The camera constructor should contain the connection parameters. – jdweng Jan 20 '22 at 17:48

0 Answers0