Search Unity

Newbie at coding. get error ! help

Discussion in 'Editor & General Support' started by RayConEX, Oct 29, 2018.

  1. RayConEX

    RayConEX

    Joined:
    Oct 29, 2018
    Posts:
    4
    i get following error : NullReferenceException: Object reference not set to an instance of an object
    playercontroller.Update () (at Assets/playercontroller.cs:21)

    if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100))


    What did i do wrong? I personally think is something with the camera? but not sure.


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


    public class playercontroller : MonoBehaviour {

    NavMeshAgent Agent;

    private void Start()
    {
    Agent = GetComponent<NavMeshAgent>();
    }
    private void Update()
    {
    if (Input.GetMouseButtonDown(0))
    {

    RaycastHit hit;
    if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100))
    Agent.destination = hit.point;
    }
    }
     
  2. lipisis

    lipisis

    Joined:
    Jan 14, 2017
    Posts:
    20
    Most likely NavMeshAgent is not attached to the same object this script is attached to,
    GetComponent<NavMeshAgent>()
    looks for the NavMeshAgent only on the same object like script is.
     
  3. RayConEX

    RayConEX

    Joined:
    Oct 29, 2018
    Posts:
    4
    i have put on a photo, to me it seems like is the same object it´s on.

    could have done anything wrong with the Ground since i just took one from asset?
     

    Attached Files:

  4. Hullabu

    Hullabu

    Joined:
    Oct 23, 2014
    Posts:
    17
    If you have an error in this string:
    "if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100))"
    check your Main Camera object. It must has "MainCamera" tag.
     
  5. RayConEX

    RayConEX

    Joined:
    Oct 29, 2018
    Posts:
    4

    Is the tag "Main Camera" ??? or where do i see it ?

    I tried to rename the file "MainCamera" Aswell, didn´t work.
     

    Attached Files:

    Last edited: Oct 30, 2018
  6. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    6,253
    Click on the object with contains the camera, and at the top of the inspector look at what tag is set. Also, your code is difficult to read because you're not using CODE tags when posting to the forum, and linking image thumbnails like you're doing is basically useless.
     
    RayConEX likes this.
  7. RayConEX

    RayConEX

    Joined:
    Oct 29, 2018
    Posts:
    4
    Wow.. something so simple.. well thanks alot brow that totally sloved the problem! i will use the code thing next time aswell ! ty