- Home /
The question is answered, right answer was accepted
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:
When clicked on any planet under the system GameObject, system GameObject is SetActive to false. Corresponding planet under planets GameObject is SetActive to true.
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 :)
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);
}
}
}
This tag distinguish between planets rendered in solar system (with tag Big) and alone (without tag Big). When planet clicked in solar system is clicked (so with tag Big), solar system should disappear (and it does) and planet alone appear (and it does). Then, when planet shown alone is clicked (without tag Big) it should disappear (and it does) and solar system appear (and it doesn't).
What are systemSL and planetSL? And Where is this script ( in which object/s )?
Planets in System object and Planets object or only in Planets object
Answer by pmduda · Aug 11, 2017 at 11:48 AM
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);
}
Follow this Question
Related Questions
GameObjects that I deactivate are reactivated immediately 0 Answers
c# Set Active error, conflicting with other code.. 1 Answer
Panel GameObject not activating 0 Answers
GameObject.setActive(bool) is not activating my gameObject 1 Answer
Panel GameObject not activating when called from another script 1 Answer