Javascript - NullReferenceException: Object reference not set to an instance of an object levelclick.Start () (at Assets/Scripts/levelclick.js:29)

I’m making a level menu. I have a variable in PlayerPrefs called ‘cleared’, and it reads that, and for each level button, it checks cleared to see if it’s high enough for that, and enables/disables the button accordingly. I don’t have it for the level 1 button, because it should be enabled no matter what. HOWEVER! I keep getting this error, and the game works fine anyways, but it’s annoying. When I click on the error in the console, it highlights the level 1 button object… which makes no sense because the script doesn’t say anything about that gameObject at all. As you can see from the title it says the error’s on line 29 (which is weird because level 29 is like all the rest of the lines). The game works fine anyways but it’s annoying as hell. Can anyone spot the problem? Thanks!

#pragma strict

var loading : GameObject;
var level = "";
private var loadinglevel = false;
private var levelsavailable = 0;
private var level2button : GameObject;
private var level3button : GameObject;
private var level4button : GameObject;
private var level5button : GameObject;
private var level6button : GameObject;
private var level7button : GameObject;

function Start () {
	loading = GameObject.Find("loadingscreen");
	loading.renderer.material.color.a = 0;
	level2button = GameObject.Find("level2");
	level3button = GameObject.Find("level3");
	level4button = GameObject.Find("level4");
	level5button = GameObject.Find("level5");
	level6button = GameObject.Find("level6");
	level7button = GameObject.Find("level7");
	levelsavailable = PlayerPrefs.GetInt("cleared") + 1;
	
	if (levelsavailable >= 2) {
		level2button.SetActive(true);
	}
	else {
		level2button.SetActive(false);
	}
	
	if (levelsavailable >= 3) {
		level3button.SetActive(true); 
	}
	else {
		level3button.SetActive(false); 
	}
}


function OnMouseDown () {
	gameObject.renderer.material.color = Color(0.666, 0.666, 0.666);
}

function OnMouseUp () {
	gameObject.renderer.material.color = Color(1, 1, 1);
	loadinglevel = true;
}

function FixedUpdate () {
	if (loadinglevel) {
		loading.transform.position.z = -5;
		if (loading.renderer.material.color.a >= 1) {
			loadinglevel = false;
			Application.LoadLevel(level);
		}
		else {
			loading.renderer.material.color.a += .02;
		}
	}
}

The error is thrown because, while executing the Start() function the GameObject is not created yet (or is not fully activated).
That’s why , the GameObject.Find() has returned a null value to ‘level2button’.
and you are trying to deactivate that object which is null.

I suggest you run the if-else code snippet in Update(). I know you want to execute it only once, so use some flag.

Mark as solved if this helps…