I’m trying to make a simple text-based game in C#. How I want to achieve this is by adding labels to a form (instead of using the command prompt). I’m having some trouble adding them to the screen. Visual studio is giving an unspecified error (Only saying I have an unhandled exception):
Object reference not set to an instance of an object
when I try to use an array to populate the screen with these labels. The code:
private void Main_Game_Load(object sender, EventArgs e)
{
Label[] Enemies = new Label[20];
Label[] Projectile = new Label[5];
Font font = new Font(new System.Drawing.FontFamily("Microsoft Sans Serif"), 12);
Random rand = new Random();
Point point = new Point(rand.Next(500), rand.Next(500));
for (int i = 0; i < Enemies.Length; i++)
{
Enemies[i].Text = "E";
Enemies[i].Font = font;
Enemies[i].BackColor = ColorTranslator.FromHtml("#000000");
Enemies[i].Location = point;
Enemies[i].Size = new Size(12, 12);
Enemies[i].Name = "Enemy"+i.ToString();
this.Controls.Add(Enemies[i]);
}
}
I am wondering where the issue might be hiding at? I’ve googled it and my code seems like it should work (aside from right now point doesn’t randomize on attempt to populate).
This line of code creates an empty array (i.e. each element referencing to nothing) to store up to 20 labels:
You must create each label in the array explicitly:
From Single-Dimensional Arrays (C# Programming Guide):