I have a boolean that checks wether an enemy is in sight and if so the unit will stop moving. When I execute the script however I get a null reference exception saying; “object reference not set as an instance of this object**”**
error line is in script2; if(gameObject.GetComponent().FindPath){
Below are the two scripts thats are communicating trough the boolean FindPath.
voidLateUpdate(){
if(gameObject.GetComponent<Turret>().FindPath){ //this is the error line null reference exception
transform.GetComponent<NavMeshAgent>().destination=Destionationpoint.position;
}
}
I dont think it is a null reference exception on the boolean, but more on the GetComponent. Perhaps for some reason it didnt find it. You should always try to include the check to see if the GetComponent returned null. If so, the rest of that should be avoided.
As the others have said, this is happening because there’s no OverlapSphere component attached to your gameObject.
If the script you posted needs an OverlapSphere, you could use the RequireComponent tag to make sure that it’s always added when it’s needed. Or, you could add it to the gameobject on Awake:
If you haven’t redeclared gameObject field inside Move script, then it still references the game object that this Move script is attached to.
When you execute gameObject.GetComponent(), the function returns a reference to the OverlapSphere component that is attached to this game object. If there’s no OverlapSphere component attached to this game object, GetComponent returns a null reference. And if it does return a null reference, then reading or writing its FindPath field will generate NullReferenceException.