Question by
vespera · Apr 28, 2016 at 06:15 PM ·
c#navmeshnavmeshagentnavigation
Object reference not set to an instance of an Object?
Hi, I'm new to Unity, I've backed a Navmesh in my game and wanted to use mouse click to set destination for player, but I got this error in console so the agent doesn't move at all, can someone explain where went wrong? The error is in the line "if (Physics . Raycast (Camera .main. ScreenPointToRay (Input .mousePosition), out hit, 100)) ". Here my script:
using UnityEngine;
using System.Collections;
public class Navmesh : MonoBehaviour {
NavMeshAgent agent;
void Start () {
agent = GetComponent<NavMeshAgent>();
}
void Update () {
if (Input.GetMouseButtonDown (0))
{
RaycastHit hit;
if (Physics . Raycast (Camera .main. ScreenPointToRay (Input .mousePosition), out hit, 100))
{
agent.destination =hit.point;
}
}
}
}
Comment
That should work. $$anonymous$$aybe the camera is null, do you have a camera tagged as $$anonymous$$ainCamera in the scene?
are you sure it's not agent.destination
causing the error? I see situations where agent
might be null. (edit: oops, meant to add comment, not reply...whatever)