GameObject Find - NullReferenceException: Object reference not set to an instance of an object

using UnityEngine;
using System.Collections;

public class Buttons : MonoBehaviour {

	public GameObject FoundObject;
	//public string TagName = "directionalImage";
	int randomNumber;
	int i, j;
	public void OnButtonClick(int num) {

		//Debug.Log("Clicked : "+ num);
		//FoundObject = GameObject.FindGameObjectsWithTag(TagName);

		for (i = 1; i < 5; i++) {
			if(GameObject.Find("DirectionalImage_"+num.ToString()).activeInHierarchy) {
					Debug.Log("Awesome");
			}
			else {
				Debug.Log("Wrong");
			}
		}

		randomNumber = Random.Range(1, 4);
		GameObject.Find ("DirectionalImage_1").SetActive (false);
		GameObject.Find ("DirectionalImage_2").SetActive (false);
		GameObject.Find ("DirectionalImage_3").SetActive (false);
		GameObject.Find ("DirectionalImage_4").SetActive (false);

		GameObject.Find("DirectionalImage_"+randomNumber.ToString()).SetActive(true);
	}
	
}

NullReferenceException: Object reference not set to an instance of an object
Buttons.OnButtonClick (Int32 num) (at Assets/Scripts/Buttons.cs:26)

That 26th line is GameObject.Find (“DirectionalImage_2”).SetActive (false);

There are four images. Random image is set to active. Other three images are set to inactive.
Once the button is pressed. I inactivate all the images and randomly choose one image to be active.

GameObject.Find doesn’t find inactive objects. You need to use global variables or something similar.

If anyone will find it interesting:

I had the problem with buttons. Once you pressed it went inactive. The next time the script is initialized i had a check if(GameObject.Find("ETower1").activeSelf == true), which was throwing:

GameObject Find - NullReferenceException: Object reference not set to an instance of an object

The solution for me was just to check if it is null before looking for it:
if (GameObject.Find("ETower1") !=null && GameObject.Find("ETower1").activeSelf== true)
hope it help anyone, it was soo simple.

The root of your problem lies as so;
When you use GameObject.Find(“object name”) sometimes it returns a null if no object is found, however you are trying to access information on that null object with “.activeInHierarchy” and so on. To avoid this, you need to make a variable before that:

GameObject go = GameObject.Find("DirectionalImage_"+num.ToString());

//then check if the object is not null
if(go){    //or use (go != null) if you prefer
    //EXECUTE CODE HERE
    if(go.activeInHierarchy){
        Debug.Log("Awesome");
    }else{
        Debug.Log("Wrong");
    }
}