Reenabling GameObject with SetActive - NullReferenceException

Hi!

I’m trying to enable a gameobject, that was disabled earlier by the same script. Here is my starting scene setup:

Action is as follow:

  1. When clicked on any planet under the system GameObject, system GameObject is SetActive to false. Corresponding planet under planets GameObject is SetActive to true.
  2. When clicked on planet under the planets GameObject it is SetActive to false, and system GameObject is SetActive to true.

However, that last action generates:
NullReferenceException: Object reference not set to an instance of an object
planetClick.OnMouseDown () (at Assets/Scripts/planetClick.cs:36)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)

Here is my code, please help :slight_smile:

public class planetClick : MonoBehaviour {

	private GameObject solarSystem;
	private GameObject Planets;
	private GameObject planet;
	private string clickedPlanetName;
	private string clickedPlanetTag;

	void Awake()
	{
		solarSystem = GameObject.FindGameObjectWithTag("SolarSystem");
		Planets = GameObject.FindGameObjectWithTag("Planets");
	}


	void OnMouseDown()

	{
		clickedPlanetName = gameObject.name;
		clickedPlanetTag = gameObject.tag;

		if (clickedPlanetTag == "Big")
		{
			solarSystem.SetActive(false);
			Planets.transform.Find(clickedPlanetName).gameObject.SetActive(true);
			Planets.transform.Find("planetsSL").gameObject.SetActive(true);
		}
		else
		{
			Planets.transform.Find(clickedPlanetName).gameObject.SetActive(false);
			Planets.transform.Find("planetsSL").gameObject.SetActive(false);
			solarSystem.SetActive(true);
		}
	}
}

OK - I found the problem - object on which I clicked to reenable solar system was enabled after solar system was disabled.

So changing the if statement into this solved the problem:

if (clickedPlanetTag == "Big")
		{
			Planets.transform.Find(clickedPlanetName).gameObject.SetActive(true);
			Planets.transform.Find("planetsSL").gameObject.SetActive(true);
			solarSystem.SetActive(false);
		}