Destroyed Objects causing errors (transform/setdestination)

Hello,
after a Long Research I couldn’t move on and now I am asking this question…

First off: my Code to find the enemy

using UnityEngine;
using System.Collections;


public class UndeadFindEnemy : MonoBehaviour
{
	Transform playereast;
	Transform playereastbuilding;
	NavMeshAgent nav;


	void Start ()
		{
		playereast = GameObject.FindGameObjectWithTag ("PlayerEast").transform;
		playereastbuilding = GameObject.FindGameObjectWithTag ("PlayerEastBuilding").transform;
		nav = GetComponent <NavMeshAgent> ();
		}


	  private void FixedUpdate ()
		{

		 if (WithinArea (50.0f, "PlayerEast"))
		{
			if (playereast != null) 
			nav.SetDestination (playereast.position);
		}

		  	else
			{
			if (playereast != null) 
			nav.SetDestination (playereastbuilding.position);
			}
		}


	 private bool WithinArea (float distance = 10.0f, string tag = "PlayerEast")
		 {

		 GameObject[] targets = GameObject.FindGameObjectsWithTag ("PlayerEast");
		 var close = false;
		 foreach (GameObject target in targets)
				  {
				   close = Vector3.Distance (transform.position, target.transform.position) < distance ? true : false;
				  }

						return close;

				}

}

my Health Codes:

	if(currentHealth <= 0)
	{
		isSinking = true;
		Death ();
	}

	if(isSinking)
	{
		transform.Translate (-Vector3.up * sinkSpeed * Time.deltaTime);
	}

void Death ()
{
	GetComponent <NavMeshAgent> ().enabled = false;
	Destroy (this.gameObject, 2f);
}

MissingReferenceException: The object of type ‘Transform’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Transform.get_position ()

“SetDestination” can only be called on an active agent that has been placed on a NavMesh.
UnityEngine.NavMeshAgent:SetDestination(Vector3)

When the first object get below 0 life and start sinking the SetDestination error occurs, which is gone after 2 seconds,

but the Transform error is Happening every Frame and my objects won’t retarget any other object.

I have no idea what’s going on…
…thank you,
Flowered

Once your object starts sinking it technically falls below the navemesh making it impossible for the other objects to track/follow it. But at this time it still exists within the game.

Try using a technique similar to ragdoll. When your object reaches zero health instantiate a copy of it (doesn’t need an scripts or any controllers just need to look like the object)

Anyway… instantiate this copy AND destroy the original at the same time. You won’t notice any visual change, your object will still appear to sink and the destroyed object will be removed from the scene.

:slight_smile: