Click to move NavMeshAgent Script not working... please help!
Hello, I've been looking through forum for quite a while and couldn't find an answer to my problem. I must say I am a begginer, but I've been trying to put up a click to move script so my Character can walk on the navmesh as a navmesh agent. Here is my script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class ClickToMove : MonoBehaviour
{
NavMeshAgent navMeshAgent;
void Start()
{
navMeshAgent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
GetInteraction();
}
void GetInteraction()
{
Ray interactionRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit interactionHit;
if (Physics.Raycast(interactionRay, out interactionHit))
{
navMeshAgent.destination = interactionHit.point;
}
}
}
The thing is, its not working at all.
I've baked the navmesh, added a navmeshagent component to my capsule, assigned the script to it, but it always return my a NullReferenceException: object reference not set to an instance. I also tried pre-made scripts I found on the internet and it does the exact same error so I guess the error is either on my side or related to the newer versions of Unity Im using.
Thank you for your help, I appreciate it.
Answer by rob11 · Sep 07, 2018 at 01:38 AM
Hello, after a few more hours of searching the internet and re-reading my script, I finally understood what was going wrong:
I needed to assign the "MainCamera" tag to the Main Camera game object, I presumed that Unity automatically knew what was the main camera, it's my bad.
Your answer
Follow this Question
Related Questions
NavMeshAgent not teleport on y axis 0 Answers
How to get Agent to Destroy Buildings and Fix Pathing? 0 Answers
ai patrol and chase question 0 Answers
Need help with Nav Mesh Agent getting "stuck" at high speeds 0 Answers
Problem with NavMesh 0 Answers