Question Need some help setting up a dynamic array

BullDog94

New member
Joined
Feb 9, 2013
Messages
1
Programming Experience
Beginner
Hello, I'm just beginning to learn VB.net and need some help with my programme. It's a game that I've been making through following tutorials on YouTube and there is an error which I don't know how to fix. Essentially in this 2D game you are a ship (picture box) at the bottom of the screen and you have these aliens (picture boxes) appearing at the top of the screen and working their way down from left to right and then moving down once they hit a border.

I had this working with just one picture box however now I've tried to add a dynamic array in which a pre-set number of aliens will appear. There are no errors in the error list however when I click on run (the play button) it comes up with "Object reference not set to an instance of an object." which after some research turns out to be because where it says Aliens(x).Left += AlienSpeed it cannot do the .Left bit because there is no value for Alien(x) which I don't know how to fix, the whole sub is below for MoveAlien if that is helpful, I've also put a ">" at the start of each line where the error appears. Many thanks, Bulldog94

Private Sub MoveAlien()
For Me.x = 1 To NumOfAliens
If AlienRight(x) = True Then
> Aliens(x).Left += AlienSpeed
Else
> Aliens(x).Left -= AlienSpeed
End If


> If Aliens(x).Left + Aliens(x).Width > Me.ClientRectangle.Width Then
AlienRight(x) = False
> Aliens(x).Top += AlienDrop
End If


> If Aliens(x).Left < Me.ClientRectangle.Left Then
AlienRight(x) = True
> Aliens(x).Top += AlienDrop
End If
Next
End Sub
 
Last edited:
there is no value for Alien(x)
Presumably you have created an array, but you haven't created and put any objects in your array yet. To create new objects you must use the New keyword, for example New PictureBox

Instead of dynamically resizing an array use a List(Of T) collection, where T is the type of the objects you want to put in it.
 
Hi,

In addition to JohnH's comments, the reason why your code is not working is that all arrays and collections in .NET are indexed from zero and your For loop is trying to access an index outside of the array bounds with the way you have it structured now.

The correct way is iterate through the elements of your array / or list, should you wish to change, is to go from index 0 to index Array.Length - 1. i.e:-

VB.NET:
For x = 0 To NumOfAliens - 1

Hope that helps.

Cheers,

Ian
 
The correct way is iterate through the elements of your array / or list, should you wish to change, is to go from index 0 to index Array.Length - 1. i.e:-
VB.NET:
For x = 0 To NumOfAliens - 1
Good catch, I totally overlooked that. It could and would be the reason for error if there were objects in array and x exceeded boundary, IndexOutOfRangeException would then be thrown at that index.
 

Latest posts

Back
Top