- Home /
How do I instantiate a class Object, then store it in an Array of Class Objects in C#?
I'm trying to create an array of class objects containing the info on the different player characters in an RPG. I created a class called CharacterAttributes that holds all the information about each character. That class has a few simple methods for leveling up etc.
But I can't for the life of me figure out how to create the class object, the fill it with information, then store it in an array. I get the error "NullReferenceException: Object reference not set to an instance of an object".
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PartyInfo : MonoBehaviour {
public List<GameObject> partyArray;
// Use this for initialization
void Start () {
GameObject charlie = new GameObject();
charlie.name = "Character Object";
charlie.AddComponent<CharacterAttributes>();
GameObject.Find("Character Object").GetComponent<CharacterAttributes>().Init(Player.Charlie,"Charlie", CombatPosition.PlayerFrontCenter, "TBA", Element.none, Element.none, 6, 6, 6, 6, 6, 6, 6, 56000);
Debug.Log (GameObject.Find("Character Object").GetComponent<CharacterAttributes>().mName);
AddCharacter(charlie);
}
// Update is called once per frame
void Update () {
}
void AddCharacter( GameObject character) {
partyArray.Add(character);
}
}
I've tried a lot of different things. I tried converting my class to a ScriptableObject, but got the same result. This code represents my attempt to create an empty game object, then attach my script to it, then call that object by name. I get a "Character Object" in my hierarchy when I run the script, but that's it. I clearly am missing something pretty basic here. Any help would be much appreciated.
Answer by JoshuaBam · Apr 30, 2013 at 03:02 AM
You do not have an instance of your List<>, so you get a null reference when you execute partyArray.Add().
Try: public List< GameObject > partyArray = new List< GameObject >();
Your answer
![](https://koobas.hobune.stream/wayback/20220613101245im_/https://answers.unity.com/themes/thub/images/avi.jpg)