1

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).

2 Answers 2

3

This line of code creates an empty array (i.e. each element referencing to nothing) to store up to 20 labels:

Label[] Enemies = new Label[20];

You must create each label in the array explicitly:

for (int i = 0; i < Enemies.Length; i++)
{
    //creates a new label and stores a reference to it into i element of the array 
    Enemies[i] = new Label(); 
    //...
}

From Single-Dimensional Arrays (C# Programming Guide):

SomeType[] array4 = new SomeType[10];

The result of this statement depends on whether SomeType is a value type or a reference type. If it is a value type, the statement creates an array of 10 elements, each of which has the type SomeType. If SomeType is a reference type, the statement creates an array of 10 elements, each of which is initialized to a null reference.

Sign up to request clarification or add additional context in comments.

Comments

2

When you create the array all of the elements are populated with the default value of that type. For all reference types that's null. You need to actually create a new Label for each item in the array:

for (int i = 0; i < Enemies.Length; i++)
{
    Enemies[i] = new Label();
    //...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.