How do I avoid the NullReference Error when I am waiting to target something?

Kinda hard to explain but I’ll try my best.

I have a game that has me going around targeting the closest food object, within a certain distance.

I don’t have any issues if I set the distance to Mathf.infinity but if I need it to be a short range, I get the NullReference Error. I know why I am getting it, I have a few things refering to the target, but the target is currently null. The error goes away once I’ve gotten close to the food, and the food object becomes my target.

I tried doing if (target != null) Kinda thing but maybe I’m doing it wrong? Here are my scripts:

Thanks in advanced

	void Update () 
		{
			Vector3 temp = gameObject.transform.localPosition;
				
			gameObject.transform.localPosition = temp;
			

		target = FindClosestEnemy().gameObject; //this is one of the error givers.
			
			if (target != null)
		{

			var newRotation = Quaternion.LookRotation(Vector3.forward, transform.position - target.transform.position);
			newRotation.x = 0.0f;
			newRotation.y = 0.0f;
			transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * 60);
			

			NanoFoodController tempfood = FindClosestEnemy().gameObject.GetComponent<NanoFoodController>();  
		 	
			tempfood.MakeFoodSmaller(); //this one here also gives the null error


		
		public GameObject FindClosestEnemy() 
		{
			GameObject[] gos;
			gos = GameObject.FindGameObjectsWithTag("Enemy");
			GameObject closest = null;
			float distance2 = Mathf.Infinity;
			float distance = 4;
			Vector3 position = transform.position;
			foreach (GameObject go in gos) {
				Vector3 diff = go.transform.position - position;
				float curDistance = diff.sqrMagnitude;
				if (curDistance < distance) {
					closest = go;
					distance = curDistance;
				}
			}

			return closest;
			
			
		}

It is always recommend to avoid method chaining with methods like GetComponent<…>(), Find() and so on because you cannot rely on the return value not being null.

In this case you still have possible points of failure which can cause NullReferenceExceptions.
The following two lines contain 2 methods that shouldn’t be chained, your own FindClosestObject as you cannot know whether it return an GO or not, and GetComponent<>.

This being said, break the following

NanoFoodController tempfood = FindClosestEnemy().gameObject.GetComponent<NanoFoodController>();  
              
             tempfood.MakeFoodSmaller(); //this one here also gives the null error

down into this and check the console:

GameObject closestGO = FindClosestEnemy();
if(closestGO != null)
{
    NanoFoodController tempfood = closestGO.GetComponent<NanoFoodController>();
    if (tempfood != null)
        tempfood.MakeFoodSmaller();
    else
        Debug.Log("tempfood is null");
}
else
{
    Debug.Log("closestGO is null");
}