-3

I am trying to use a raycast that writes the name of the object that hits and the position and when shooting the ray it gives a null reference exception. It happens at this line Ray ray = cam.ScreenPointToRay(Input.mousePosition); Here is the code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{

Camera cam;

// Start is called before the first frame update
void Start()
{
    cam = Camera.current;
}

// Update is called once per frame
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        //a ray is created
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        //it is then casted
        if (Physics.Raycast(ray, out hit))
        {
            Debug.Log("We have hit " + hit.collider.name + " " + hit.point);
            
        }
    }
}
}
  • So probably something is null. Did you debug to figure it out? Also, rather than give us a line number expecting us to count the lines (hoping you pasted in the right code), you could make it a little easier and actually mark which line. – Xerillio Aug 22 '21 at 15:27
  • Did you place a camera? `Camera.current;` may be null? – MaartenDev Aug 22 '21 at 15:38

1 Answers1

1

The property Camera.current

The camera we are currently rendering with, for low-level render control only (Read Only).

is only set/valid within the event messages OnRenderImage, OnPreRender and OnPostRender

the rest of the time it is null.


You want to rather use Camera.main!

The first enabled Camera component that is tagged "MainCamera" (Read Only).

derHugo
  • 83,094
  • 9
  • 75
  • 115