- Home /
Question by
MattSawrey · Feb 11, 2014 at 10:57 PM ·
objectinstanceclasses
Object Instance Error Message Confusion
The script below is giving me the following error message and I have no idea why:
"NullReferenceException: Object reference not set to an instance of an object Characters.Start () (at Assets/Scripts/Character/Characters.cs:31)"
As far as I can see, everything is correct. Am I missing something?
public class Traits
{
public int id;
public string name;
public int strength;
public int agility;
public void characterData()
{
print("id: " + id + "Name: " + name + " Strength: " + strength + " Agiligty: " + agility);
}
}
void Start()
{
Traits[] character = new Traits[51];
for (int i = 1; i <= 50; i++)
{
character[i].id = i;
character[i].name = "Jeff";
character[i].strength = 20;
character[i].agility = 20;
}
for (int i = 1; i <=10; i++)
{
character[i].characterData();
}
}
}
Comment
Best Answer
Answer by rutter · Feb 11, 2014 at 11:26 PM
You're close, but computers are so very picky.
Traits[] character = new Traits[51];
This creates an array that is full of null references. In simple terms, you've created 51 boxes, but there's nothing in the boxes yet. You'll need to populate the array with objects before you can access them.
Since you're already looping through the array, something like this could do the trick:
for (int i = 1; i <= 50; i++)
{
character[i] = new Traits(); //notice this line I added
character[i].id = i;
character[i].name = "Jeff";
character[i].strength = 20;
character[i].agility = 20;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613133234im_/https://answers.unity.com/themes/thub/images/avi.jpg)