I’m just starting C#, and creating my first game, but just ran into a problem.
I have a picturebox array
PictureBox[] obstacles = new PictureBox[20];
And I’m trying to declare 20 new random location pictureboxes inside it.
private void Game_Load(object sender, EventArgs e)
{
player.Size = new Size(20, 20);
player.Location = new Point(20, 240);
player.Image = Properties.Resources.playerImg;
Controls.Add(player);
for (int i = 0; i < 20; i++)
{
obstacles[i] = new PictureBox();
obstacles[i].Size = new Size(10, 10);
obstacles[i].Location = new Point(50, 340);
obstacles[i].BackColor = Color.Red;
Controls.Add(obstacles[i]);
}
}
I know it’s not spawning them into a random location yet, but I won’t do that ’till I get them to spawn at all.
Now when I try to create a method to use picturebox array, it’s objects (picturebox[0-19]) are all just null?
private void JustAnOtherTest(PictureBox obj)
{
for (int y = obj.Top; y < obj.Top + obj.Height - 1; y++)
{
MessageBox.Show("Testing out!", "Test");
}
}
Now calling: JustAnOtherTest(obstacles[1]); and adding a watch for obj in JustAnOtherTest method will just give me a null, why is that?
EDIT: Seems like it never goes into the for loop, cause it exits Game_Load once it gets to player.Image = Properties.Resources.playerImg; which probably means that the problem is in the resource files… :S
EDIT2: Yeah, I was right, the problem was within resource files. I had messed up with some namespaces and it couldn’t find the resource file cause it was in a different namespace, but I ain’t so sure why it didn’t give an error on that. How ever, after fixing all the namespaces, works just fine. 🙂
There are three possibilities
1) Game_Load() is not being called before you access the array. Stick a break point in it and see if it fires.
2) You are somehow creating two variables called obstacles. Where is it defined exactly?
3) Something is clearing it again before you access it.
The most basic check is to put a breakpoint in your create loop, and check that the new is working ok at that point.