array initialisation c#

Hi peepz

I have a silly problem. I have 2 scripts, a master and a guicontrol. the masterscript knows every gameobjects in my scene and have a little function to pass the gameobject array to other scripts:

using UnityEngine;
using System.Collections;

public class MasterScript : MonoBehaviour {
		
	private GameObject[] GatesInSpace;
	private GameObject[] FightersInSpace;

	// Use this for initialization
	void Start () {
		GatesInSpace = GameObject.FindGameObjectsWithTag("Gate");
		FightersInSpace = GameObject.FindGameObjectsWithTag("Fighter");
	}
	
	// Update is called once per frame
	void Update () {
		FightersInSpace = GameObject.FindGameObjectsWithTag("Fighter");

		Debug.Log ("Gates: " + GatesInSpace.Length);
		Debug.Log ("Fighters: " + FightersInSpace.Length);
	}

	public GameObject[] GetGates() {
		return GatesInSpace;
	}

	public GameObject[] GetFighters() {
		return FightersInSpace;
	}
}

based on the debug it works well, it find the objects…

the other script:

using UnityEngine;
using System.Collections;

public class MapGUI : MonoBehaviour {

	public Texture MapGate;
	public Texture MapShip;
	public MasterScript MasterScript;

	// Use this for initialization
	void Start () {
	}
	
	// Update is called once per frame
	void Update () {

	}

	void OnGUI () {
		int a = MasterScript.GetGates().Length;
		
	}
}

sadly throw a nullreference exception :frowning:

why?

A guess would be that you have not assigned a value to the MasterScript variable. Try to assign it in the inspector for the GameObject that has the MapGUI component.

Another bugtest you can do is to add debug right before using the master script just to check what is actually null:

//For example something like this
Debug.Log("Masterscript is: " + MasterScript);
Debug.Log("GetGates() is: " + MasterScript.GetGates());

Also as a general coding convention: Class/Types has uppercase names while variables has lowercase names. This avoids confusion and lowers chances of errors.

//Instead of this
public MasterScript MasterScript;

//Use this
public MasterScript masterScript;