I'm creating a simple game as a Windows Form Application and am trying to program collision detection between the player's picture box, and walls within the game, which are also picture boxes. Instead of having to program every wall with an IF statement I decided to use a For loop.
I first put the picture boxes into an array:
Dim walls() As PictureBox = {wall1, wall2, wall3, wall4, wall5, wall6, wall7, wall8, wall9, wall10, wall11, wall12, wall13, wall14, wall15}
Which I then used to loop through as the collision detection (picCar is the player):
For x As Integer = 0 To 14 'I also tried this with "1 To 1"
If picCar.Bounds.IntersectsWith(walls(x).Bounds) Then
If lives > 1 Then
lives -= 1
movetostart()
Else
MsgBox("Game Over!")
End If
End If
Next
This returned a "NullReferenceException was unhandled" error so I tried it within a For Each loop instead:
For Each wall As PictureBox In walls
If picCar.Bounds.IntersectsWith(wall.Bounds) Then
If lives > 1 Then
lives -= 1
movetostart()
Else
MsgBox("Game Over!")
End If
End If
Next
This returned the same error. I'm not quite sure what I'm doing wrong? I found and tested both these ideas through other threads and cannot find much else on the matter, would you be able to help?
Links to threads: