NullReferenceException Error

This is the error message i get when i run it.

NullReferenceException: Object reference not set to an instance of an object Player.Update () (at Assests/Scripts/Player.cs: 16)

This is the code.

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

public class Player : MonoBehaviour
{
//Variables
public float movementSpeed;

//Functions
void Update()
{
//Player movement
Plane playerPlane = new Plane(Vector3.up, transform.position);
Ray ray = UnityEngine.Camera.main.ScreenPointToRay(Input.mousePosition);
float hitDistance = 0.0f;

if (playerPlane.Raycast(ray, out hitDistance))
{
Vector3 targetPoint = ray.GetPoint(hitDistance);
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
if (Input.GetMouseButtonDown(0))
{
print(targetPoint);
}
}
}
}

The error tells you that line 16 contains the problematic call. If there are no other lines in your code than the ones you showed, there is a high probability that there is no main camera in your scene. In editor, simply double-click on the error message, and usually it will take you to the offending line in the code.

-ch

That’s all the code. And i have a main camera. I don’t know what’s the problem. :frowning:

Double-click on the offending line, and copy the line that is throwing the exception here, together with the error you are getting. Maybe we can figure it out then.

Urgent
Use code tags properly.

Ray ray = UnityEngine.Camera.main.ScreenPointToRay(Input.mousePosition);
This is the code that’s highlighted.

Sorry about that. New here, going to rename this post.

In that case, einter Camera or Input aren’t defined. Break up the code to narrow down the issue:

Camera mainCam = UnityEngine.Camera.main;
if (mainCam == null) Debug.Log("No Camera!");
Vector3  mp = Input.mousePosition;
Ray r = maincam.ScreenPoint(mp);

No problem, looks better. If you just edit post and apply code tags, so look similar like @csofranz , it will be spot on.

3876481--329203--upload_2018-11-10_13-36-44.png

PS. Just let you know, you got post duplicate btw.