Creating a static array of a class

Here’s my problem: I’m working on an RPG and I have created public classes to handle characters. These classes include all the information that would be stored on the character (their name, their attributes, life pool, skills, etc) as well as many methods that might be commonly called.

Here’s an example of what I mean:

public class Character {
	// Name and Class Information:
	string _name;
	string _classname;
	int _class;
	// Attributes:
	int _str;
	int _int;
	int _agi;
	int _wil;
// Character Name:
public string CharacterName
	get {return _name; }
	set {_name = value; }
// Character Strength:
public int Strength
	get {return _str; }
	set {_str = value; }
// Character Intellect:
public int Intellect
	get {return _int; }
	set {_int = value; }
// Character Agility:
public int Agility
	get {return _agi; }
	set {_agi = value; }
// Character Willpower:
public int Willpower
	get {return _wil; }
	set {_wil = value; }

I need to store several instances of this class (say, for example, 6) in a static array that can be reached from anywhere within my game.

I’ve done this by creating another class to handle it and called it like this:

public class vrb  {
// Object Variables:
public static Character[] PC = new Character[4];

When I attempt to use these classes in code, Monodevelop sees them just fine, and I can do things like type: vrb.PC[1].CharacterName = “Bob Smith”; and I get no errors.

But, when I run things, I frequently get a lot of null reference errors or nothing happens at all. So, I’m hoping someone can explain to me what I need to do to make what I want happen or point me to something that will explain why it will or will not work.


you probably want to create a singleton class.

This would look something like this:

public class Controller : MonoBehaviour {

   private static Controller _instance = null;
   public static Controller SharedInstance
         if(_instance == null)
            _instance = GameObject.FindObjectOfType(typeof(Controller)) as Controller;
         return _instance;

   void Awake()
      _instance = this;
      // DontDestroyOnLoad(this)     // if you need

   // if you still want to use an array ;)
   public Character[] PC = new Character[4];


then you can access this from everywhere using


You need to attach this to a GameObject in your scene.

Also make sure you have initiated some characters / filled the array. NullReferenceExceptions can have many sources.

A singleton is also useful for a controller-role through the entire game.