9

Is it possible to create an array of objects in visual basic?

I'm making a battle system and whenever the battle begins, i wanna be able to randomly select a Monster object from an array.

If it is possible, could somebody show me how to store Public Spider as New Monster(50, 20, 5) into an array?

Thank you.

Monster Class:

Public Class Monster

  Private hp As Integer
  Private xp As Integer
  Private dmg As Integer

  Sub New(ByVal hitpoints As Integer, ByVal exp As Integer, ByVal damage As Integer)
    hp = hitpoints
    xp = exp
    dmg = damage
  End Sub

End Class

Form Class:

Imports Monster
Public Class Form

  Public Spider As New Monster(50, 20, 5)

End Class

3 Answers 3

15

A List(Of T) would work great for that.

Private Monsters As New List(Of Monster)
'later add them into this collection
Monsters.Add(New Monster(50, 20, 5))
Sign up to request clarification or add additional context in comments.

2 Comments

Ooh, beat me to it :D. +1 for you.
It's hard to tell if more than one of us are answering at one time. I got beat yesterday. =)
1

You could use one of the Collections like List(of Monster) to hold it if you don't have a set and knowable number of class instances to store.

Dim Monsters As List(of Monster) = New List(of Monster)
Monsters.Add(New Monster(10, 50, 30))

Comments

0

Of course, ArrayList is better, but your question is useful too.

  Dim MonsterArr() As Monster = New MonsterArr(1000) {}

or

  Dim MonsterArr() As Monster = New MonsterArr(1000) {0,0,0}

or

  Dim MonsterArr() As Object = New Object(1000) {}

1 Comment

Please add some explanation to your answer such that others can learn from it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.