- Home /
I get NullReferenceException when I use raycasts
Hello, I following the tutorial on NavMeshes, but ran into a little problem. What I am trying to achieve, is to move a player with a mouse click. Here's my script:
var Agent : NavMeshAgent;
function Start () {
Agent = GetComponent.NavMeshAgent;
}
function Update () {
if(Input.GetMouseButtonDown(0)){
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var Hit : RaycastHit;
if(Physics.Raycast(ray, Hit, 100)){
Agent.SetDestination(Hit.point);
}
}
}
But, when I click, I get this error message:
GoToClick.Update () (at Assets/Scripts/NavMesh AI/GoToClick.js:17) Well, the tutorial is in C#, while I prefer using JavaScript. I might just made really dump mistake. Can anyone help?NullReferenceException: Object reference not set to an instance of an object
This seems to indicate that the GameObject on which you attach GoToClick.js does not have a Nav$$anonymous$$eshAgent component attached. So, when line 5 executes the Agent variable is null (hence the error).
Nope, I have the Nav $$anonymous$$esh Agent on the same gameobject as GoToClick.js
the above code that you posted is fine and doesnt throw up any errors, it hits something on the map. test how your set destination works, it is a function(vector3):BOOL so it returns a true/false result... try calling it it without the raycast, just set
if press A, setdestination(vector3.zero)
if press B, setdestination(vector3.one)
Yeah, I don't get any errors now. Not sure how did putting everything in another test scene worked out. Anyway, sorry for your time.
Your answer
Follow this Question
Related Questions
Duplicating NavMesh Objects 0 Answers
How to prevent a NavMeshAgent to constantly spin along its y axis? 1 Answer
AI destination not changing? 0 Answers
Enabling and Disabling Nav Mesh Agent? 0 Answers