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;
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.
public Form1()
{
InitializeComponent();
stars = new PictureBox[10];
}
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,
if(stars != null) {
for (int i = 0; i < stars.Length; i++) {
}
}
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:
if(stars == null) {
stars = new PictureBox[10];
}