Search Unity

Error: Object reference not set to an instance of an object

Discussion in 'Navigation' started by Faustinoo, Oct 18, 2018.

  1. Faustinoo

    Faustinoo

    Joined:
    Oct 18, 2018
    Posts:
    1
    Hey im trying to make the player moves to where i click in the map and its showing me this error at line 20

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.AI;
    5.  
    6. public class PlayerMovement : MonoBehaviour {
    7.     NavMeshAgent agent;
    8.  
    9.     void Start()
    10.     {
    11.         agent = GetComponent<NavMeshAgent>();
    12.     }
    13.  
    14.     void Update()
    15.     {
    16.         if (Input.GetMouseButtonDown(0))
    17.         {
    18.             RaycastHit hit;
    19.  
    20.             if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100))
    21.             {
    22.                 agent.destination = hit.point;
    23.             }
    24.         }
    25.  
    26.     }
    27. }
     
  2. Yandalf

    Yandalf

    Joined:
    Feb 11, 2014
    Posts:
    491
    Make dure you have a camera in your scene that has a MainCamera tag on it, else Camera.main won't find anything.