NullReference exception when calling a static function

Hi there, I have a game object with this script attached, called DebugConsole: (shortened):

static var consoleLines:String[];

static function Write(text:String)
{
	consoleLines[consoleLines.Length]=text;
}

but when i call DebugConsole.Write("hello World"); from somewhere, I get a NullReferenceException: Object reference not set to an instance of an object at the line consoleLines[consoleLines.Length]="text";
:confused: what’s wrong?

There are two problems here.

The first is that consoleLines isn’t referencing any array.

static var consoleLines:String[] = new String[100]; // There you go...

The second one is that you’re indexing out of bounds.

consoleLines[consoleLines.Length] = text; // Wrong!

It would try to write to index 100 in my example, which doesn’t exist. Index 99 is the last index.


Just use List.<String> instead…

import System.Collections.Generic;
static var consoleLines : List.<String> = new List.<String>();    
static function Write(text : String)
{
    consoleLines.Add(text);
}

try

static var consoleLines = new Array();

static function Write(text:String)
{
    consoleLines.Add(text);
}

in other words your var consoleLines was never initialised and hence getting the length caused it to fail.

Also, note if you want to get the last entered line use consoleLines[consoleLines.length - 1] as the array is zero based.

Hope that helps

Try this (apologies if there are typos, I’m used to C# :slight_smile: You have to create the String class before you can assign text to it…

consoleLines[consoleLines.Length]=new String(text);