- Home /
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 :(
why?
Read my explanation of null references. Hopefully it'll help. See this answer.
Answer by GameVortex · Jan 13, 2014 at 02:33 PM
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;
ehhh, yes, the script was null, i love the editor... after changing the masterscript variable it removed the attached script but didnt update the inspector. after restarting unity the error was obvious :) thanks for the help
No problem. Glad to help. =) Also make sure to take a look at @Jamora comment and learn more about how to debug nullreferenceexceptions.