Elliott Welsford Elliott Welsford - 1 year ago 224
Vb.net Question

vb.net: Reference to a non-shared member requires an object reference occurs with random.next

I am attempting to randomly generate a number between (and including) 1 and 4 to randomly select an object (in this case an asteroid) and tells it to move to a location and unhide (spawn).

If Globals.pathA = True Then
Globals.astroidspawn_a1 = Random.Next(1, 4)

And then

If Globals.astroidspawn_a1 = 1 Then
astroid1.Location = New Point(800, 55)
astroid1.Visible = True
End If

This second section repeats multiple times resulting in the spawning asteroids.

The code "Random.Next" is seen as a code error, stating "Reference to a non-shared member requires an object reference".

Answer Source

You need an instance of the Random class. The preferred method is to use a Shared variable as this improves the randomness.

Place the following in your Form/Class:

Private Shared _rnd As New Random

The when you want a value:

Globals.astroidspawn_a1 = _rnd.Next(1, 4)