- Home /
How to check for null
For a dynamic menu with 4 (1,2,3,D) levels in (x amount of) missions. I have a Typer script on a text that activates when the player clicks a button but when he clicks the next button: the next Typer writes the text over the other one because both Texts are (and need to be) in the same place.
there are other solutions like using public gameobjects + SetActive but i will have a lot of buttons so this would be inconvenient so instead:
i would make a function that disables all found texts for that mission before enabling the new one but TextLevel3 will sometimes simply not exist and return null(referenceExeption) so i want to check for this and break if its null or continue if it's safe to. I'm just not sure how to do this with combined with the Gameobject.Find and GetComponent
void DisableTexts()
{
text = GameObject.Find("TextLevel1").GetComponent<Typer>().enabled = false;
text = GameObject.Find("TextLevel2").GetComponent<Typer>().enabled = false;
text = GameObject.Find("TextLevelD").GetComponent<Typer>().enabled = false;
//This is what i need:
Check if (TextLevel3 != null){go ahead} or if (TextLevel3 = null){break;(?)}
text = GameObject.Find("TextLevel3").GetComponent<Typer>().enabled = false;
}
public void CheckLevel (string selectedLevel)
{
DisableTexts();
GameObject.Find("TextLevel" + selectedLevel).GetComponent<Typer>().enabled = true;
CurrentMission = "Level" + missionSelected + "." + selectedLevel;
}
Why not just hold the text in an array/list, leave the text box blank until needed and the load the required text when needed?
text = GameObject.Find("TextLevel1").GetComponent().enabled = false;
So text is a boolean? You don't use it between the 1st and 4th times that you set it, seems a bit odd to me.
Anyway it looks to me like maybe you want something like
GameObject g = GameObject.Find("TextLevel3");
if (g != null)
{
Typer t = g.GetComponent< Typer >();
if (t !=null)
{
t.enabled = false; // or whatever else you want to do with it
}
}
That'll check not only that the object with that name exists but also that it has a Typer component. It can be that one or other of those tests isn't necessary.
You might also want else clauses that warn you when those things are null.
Your answer
Follow this Question
Related Questions
NullReferenceException: Object reference not set to an instance of an object 3 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Unexplainable NullReferenceException 2 Answers