Click here to Skip to main content
15,884,770 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm following a tutor to create a game but I'm getting an error in this line

for (int i = 0; i < stars.Length /2; i++)

C# is telling me that stars are null.

The error is System.NullReferenceException: ‘Object reference not set to an instance of an object’.

I checked the code and can see no difference in my code and your code. Maybe there is something I need to do to the form to stop this error.

The code is included.
Note that the code is not complete but this does not stop it from an giving me an error when compiling the code.

Brian_TheLion

I'm using the latest version of Visual Studio and the tutorial is for #7 of Visual Studio so maybe this is the reason for an error or there is something I needed to do that's missing in the tutorial. I've checked my code with the code in the tutorial but it's the same.



Hoping you can help me.

What I have tried:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WMPLib;

namespace SpaceShooter
{
    public partial class Form1 : Form
    {
        WindowsMediaPlayer gameMedia;
        WindowsMediaPlayer shootgMedia;
        
        PictureBox[] stars;
        PictureBox[] munitions;  //gun fire at enemy
        int backgroundspeed;
        int playerSpeed;
        int munitionsSpeed;
       
        
        Random rnd;
        public Form1()
        {
            InitializeComponent();
        }
       //window_Load methoid
        private void Form1_Load(object sender, EventArgs e)
        {
            backgroundspeed = 4;
            playerSpeed = 4;
            munitionsSpeed = 20;
            munitions = new PictureBox[3];
          
            //Load images
            Image munition = Image.FromFile(@"asserts\munitation.png");

            for(int i = 0; i < munitions.Length; i++)
            {
                munitions[i] = new PictureBox();
                munitions[i].Size = new Size(8, 8);
                munitions[i].Image = munition;
                munitions[i].SizeMode = PictureBoxSizeMode.Zoom;
                munitions[i].BorderStyle = BorderStyle.None;
                this.Controls.Add(munitions[i]);
            }

            //Create WMP
            gameMedia = new WindowsMediaPlayer();
            shootgMedia = new WindowsMediaPlayer();
          

            //Load all songs
            gameMedia.URL = "songs\\GameSong.mp3";
            shootgMedia.URL = "songs\\shoot.mp3";

            //Setup Songs settings
            gameMedia.settings.setMode("loop", true);
            gameMedia.settings.volume = 5;
            shootgMedia.settings.volume = 1;

            stars = new PictureBox[10];
            rnd = new Random();

            for (int i = 0; i < stars.Length; i++)
            {
                stars[i] = new PictureBox();
                {
                    stars[i].BorderStyle = BorderStyle.None;
                    stars[i].Location = new Point(rnd.Next(20, 580), rnd.Next(-10, 400));
                }
                if (i % 2 == 1)
                {
                    stars[i].Size = new Size(2, 2);
                    stars[i].BackColor = Color.Wheat;
                }
                else
                {
                    stars[i].Size = new Size(3, 3);
                    stars[i].BackColor = Color.DarkGray;
                }
                this.Controls.Add(stars[i]);
            }

            gameMedia.controls.play();    //might be correct place for this

        }
        //Move Game Timer_Tick
        private void MoveBgTimer_Tick(object sender, EventArgs e)
        {
            for (int i = 0; i < stars.Length /2; i++)   //ERROR on this line. stars = null
            {
                stars[i].Top += backgroundspeed;   

                if (stars[i].Top >= this.Height)
                {
                    stars[i].Top = -stars[i].Height;
                }
            }
            
            for (int i = stars.Length /2; i <stars.Length; i++)
            {
                stars[i].Top += backgroundspeed - 2;
                if (stars[i].Top >= this.Height)
                {
                    stars[i].Top = -stars[i].Height;
                }
            }
        }

        private void LeftMoveTimer_Tick(object sender, EventArgs e)
        {
            if(Player.Left > 10)
            {
                Player.Left -= playerSpeed;
            }
        }

        private void RightMoveTimer_Tick(object sender, EventArgs e)
        {
            if (Player.Right <580)
            {
                Player.Left += playerSpeed;
            }
        }

        private void DownMoveTimer_Tick(object sender, EventArgs e)
        {
            if (Player.Top <400)
            {
                Player.Top += playerSpeed;
            }
        }

        private void UpMoveTimer_Tick(object sender, EventArgs e)
        {
            if (Player.Top >10)
            {
                Player.Top -= playerSpeed;
            }
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Right)
            {
                RightMoveTimer.Start();
            }
            if (e.KeyCode == Keys.Left)
            {
                LeftMoveTimer.Start();
            }
            if (e.KeyCode == Keys.Down)
            {
                DownMoveTimer.Start();
            }
            if (e.KeyCode == Keys.Up)
            {
                UpMoveTimer.Start();
            }
        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
           RightMoveTimer.Stop();
           LeftMoveTimer.Stop();
           DownMoveTimer.Stop();
           UpMoveTimer.Stop();
        }

        private void MoveMunitionTimer_Tick(object sender, EventArgs e)
        {
            for (int i = 0; i < munitions.Length; i++)
            {
                if (munitions[i].Top > 0)
                {
                    munitions[i].Visible = true;
                    munitions[i].Top -= munitionsSpeed;
                }
                else
                {
                    munitions[i].Visible = false;
                    munitions[i].Location = new Point(Player.Location.X + 20, Player.Location.Y + 30);
                }
            }
        }
    }
}
Posted
Updated 19-Nov-19 22:26pm

The problem ist your Timer.
MoveBgTimer_Tick

This timer seems to be configured as Enabled = True in the designer.
Therefore it is immediately active after the application has started.
The event handler then accesses the stars array before it is initialized.
You should set Enabled = False in the designer and the set Enabled = True at the end of the
Form1_Load
event handler.
 
Share this answer
 
Quote:
The error is System.NullReferenceException: ‘Object reference not set to an instance of an object’.
That is one of the most basic problems developers encounter. It means that you forgot to do new for your data. It might be your code, or the code in the library and you forgot to call some sort of initialization method.

Inside your code, the problem is at,
for (int i = 0; i < stars.Length /2; i++)
Thus it means that you forgot to initialize the value for stars. If you look at the code, you see that you left the field uninitialized,
public partial class Form1 : Form
{
    WindowsMediaPlayer gameMedia;
    WindowsMediaPlayer shootgMedia;
    
    PictureBox[] stars; // <-- here
There is a simple way to solve this, just initialize the value for the stars either in the constructor, or you can do that in a separate method when you know the value for the array.
C#
public Form1()
{
    InitializeComponent();

    // Here
    stars = new PictureBox[10]; // 10 hardcoded elements, each null.
}
This brings us to another problem in C#, that the arrays are of fixed sizes. And they cannot accommodate more than their size, and will always consume the exact size in memory. This is where List<PictureBox> types come into handy.

If you can change the code, I highly recommend using a List<T> instead of an array.
.net - Array versus List<T>: When to use which? - Stack Overflow[^]
List<T> Class (System.Collections.Generic) | Microsoft Docs[^]

One more thing, I noticed that you are doing the same thing I recommended in Form1_Load method,
stars = new PictureBox[10];
rnd = new Random();

for (int i = 0; i < stars.Length; i++)
{
It would be great if you can safely continue with the execution of code. Like this,
C#
if(stars != null) {
    for (int i = 0; i < stars.Length; i++) {
        // Code here.
    }
}
This can prevent the null reference exceptions in the code.

Edit
If you want to show the stars even when they are null, just do:
C#
if(stars == null) {
   stars = new PictureBox[10];
}

// Your code here...
 
Share this answer
 
v2
Comments
Brian_TheLion 20-Nov-19 19:29pm    
Thanks for your help.
I tried putting 'starts = new PictureBox[10];' under the InitializeComponet(); code
but are now getting a similar error on this line
starts[i].Top += backgroundspeed;
however setting the MoveBhTimer to null solved this problem.
The compiler tells me that stars are null.
I had similar errors for the Munitions part of the code and made the same corrections but now when runing the program nothing happens. I should see stars moving in the sky and be able to move me spacecraft on the screen.

Any more help would be welcomed thanks.
Afzaal Ahmad Zeeshan 20-Nov-19 23:03pm    
In this case, where the access to the fields cannot be determined, you can use if...else blocks to prevent these exceptions.

This also shows the code is not being covered by tests properly.
Brian_TheLion 21-Nov-19 17:34pm    
Thanks for your help.
I tried the if (stars !=null) {..} but it blocks code from happening which results in no stars being shown.
It's strange that it works for the tutor...maybe something to do with different Visual Studio versions as he's using #7. I think I still have #7 of visual studio so I might try it using this version.
Afzaal Ahmad Zeeshan 21-Nov-19 17:42pm    
It would be great if you can check with the tutor and tell them what is wrong with the code.

I have updated the answer and added an explanation to use the code, and also to overcome the null pointer problem. Please see the last section in the answer.
Brian_TheLion 21-Nov-19 17:52pm    
I am wondering if I should have a picturebox on the form for the stars to be displayed as this was not in the tutorial.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900