- Home /
Problems With Variable Class Arrays...
I've tried researching this and am just not finding how to set this properly. What I'm trying to do is load inspector variable class arrays within a mono behaviour class attached to a game object when the game starts.
Here is what I have so far ... two variable class arrays; one nested within the other. On the inspector I can resize & edit both variable class arrays as needed. However, at run-time the start event fails with the following error message because everything is NULL (or at least the strings are):
NullReferenceException: Object reference not set to an instance of an object ClassSubClass.Start () (at Assets/_Main/Scripts/ClassSubClass.cs:36)
Here is my class code ... what am I doing wrong and how can I fix this?
using UnityEngine;
using System.Collections;
public class ClassSubClass : MonoBehaviour
{
// Sub Class Details
[System.Serializable]
public class SubClass
{
public string SubName;
public string SubText;
public int SubWeight;
public float SubMin;
public float SubMax;
}
// Main Class Details
[System.Serializable]
public class MainClass
{
public string MainName;
public string MainText;
public float MainMin;
public float MainMax;
public SubClass[] SubList;
}
public MainClass[] MainList;
// Initialization of class arrays
void Start()
{
// Load Classes
MainList = new MainClass[1];
// Populate the List
MainList[0].MainName = "First Item (0)";
MainList[0].MainText = "Hello World";
MainList[0].MainMin = 10f;
MainList[0].MainMax = 20f;
// Now the sublist
MainList[0].SubList = new SubClass[1];
MainList[0].SubList[0].SubName = "First Sub Item (0.0)";
MainList[0].SubList[0].SubText = "Hello Sub World";
MainList[0].SubList[0].SubWeight = 30;
MainList[0].SubList[0].SubMin = 40f;
MainList[0].SubList[0].SubMax = 50f;
}
void Update()
{
// Do Nothing
}
}
Arrays of classes are just a group of references to objects. By default all there references are pointing to null and no new objects are created. So you need to actually objects assign to the array after you instantiate them, i.e.
$$anonymous$$ainList[0]=new $$anonymous$$ainClass();
Answer by DiGiaCom-Tech · Jun 28, 2015 at 03:31 AM
Thank you!!! ... I knew it was going to be something simple ... Face«Palm ;)
For the record ... your solution worked flawlessly!