Null Reference Exception when reading from array of strings
Hello, I am a little confused trying to make a simple (as I thought) thing. I delared a:
public string[,] content;
then filled it with strings in a TextReader method:
public void TextReader()
{
string[,] content = new string[2, 3];
content [0, 0] = "A";
content [0, 1] = "B";
content [0, 2] = "C";
content [1, 0] = "D";
content [1, 1] = "E";
content [1, 2] = "F";
defaultText = "START";
print (content [0, 0]);
}
When I print content[0,0] from inside of the method everything is ok, but when I try to access content[0,0] or any other (content[1,2], content[0,2]) from outside I get a null exception error: object reference not set to an instance of an object.
I have put TextReader() in start:
void Start () {
TextReader ();
print (content [0, 0]);
}
And this gives me an error.
What I'm basically trying to do is put a text on a Text UI from the script. Maybe I'm missing something but if a variable is public should it be available from all methods? I'm new to programming so sorry if it's a simple misconception.
Answer by Dragate · Dec 21, 2017 at 12:04 PM
Replace
string[,] content = new string[2, 3];
with
content = new string[2, 3];
What you are doing is making content a local variable by declaring it inside the function. To access it from wherever in the class you need to have it global. You already have declared it outside the function (so that's ok), so you just need to fill it will values inside the function. Do not re-declare it.
Still a lot of learning ahead of me :-) Thanks for a very quick answer.
Your answer
