Search Unity

nav mesh agent from non connected script

Discussion in 'Navigation' started by Invictus_, Oct 8, 2016.

  1. Invictus_

    Invictus_

    Joined:
    Jul 30, 2015
    Posts:
    19
    hi,

    setting up a finite state machine for some ai project although i suspect it's going to be fairly big so i didn't want to do it all in 1 file nor put every state script on the object cause effort.

    the main ai file is put on the navmesh agent and in my chase state im attempting to pass that information through, i've tried several different ways all with no success unless i put the chase script on the object, below is just one example of what i tried in hopes it explains what im trying to do.

    NullReferenceException: Object reference not set to an instance of an object
    AI_Main.Update () (at Assets/Scripts/AI/AI_Main.cs:44)


    Code (csharp):
    1.  
    2. case State.Chase:
    3. GetComponent<AIChase>().Chase(Player, gameObject.GetComponent<NavMeshAgent>());
    4. Debug.Log("Entered Chase State");
    5. break;
    6.  


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class AIChase : MonoBehaviour {
    5.  
    6.     public void Chase(GameObject Player, NavMeshAgent Agent)
    7.     {
    8.         Agent.SetDestination(Player.transform.position);
    9.         //if this player in range of raycast of gun switch to attack state blablabla
    10.  
    11.     }
    12.  
    13. }
    14.  
    15. }
    thanks!!!
     
  2. Thorskin

    Thorskin

    Joined:
    Oct 10, 2016
    Posts:
    13
    GetComponent<AIChase>().Chase(Player, gameObject.GetComponent<NavMeshAgent>());

    first GetComponent is called on this component
    second GetComponent is called on the object contaning this component
    they are equivalent

    this obviously works only if AIChase and NavMeshAgent are attached to the same GameObject