简体   繁体   中英

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".

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)

Next() is a function that is designed to be called from an instance of the Random class. First you need to declare an object variable and initialize it, then call Next() on the object variable.

One quick way to fix the code is to instantiate a new Random class as needed before calling Next() :

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

One drawback to this approach is that random numbers aren't truly random - they are known as pseudo-random, taking a seed value and generating new numbers based on the seed. A sequence of numbers based on the same seed will be identical every time. In the example above the default seed value is based on the clock time, which means if it is called inside of a loop it has the potential to generate the same value many times in a row.

A way to fix that is to explicitly pass in a new seed to the Random object constructor that is not based on the clock time. Here's one approach:

If Globals.pathA = True Then
    Dim randomizer = New Random(Guid.NewGuid().GetHashCode())
    Globals.astroidspawn_a1 = randomizer.Next(1, 4)

This should create truly random values as the seed is then randomized as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM