Dany
Dany

Reputation: 481

How to create an array of objects Visual Basic

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

Upvotes: 9

Views: 46352

Answers (3)

Alex
Alex

Reputation: 545

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) {}

Upvotes: 0

Adrian
Adrian

Reputation: 2875

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))

Upvotes: 1

OneFineDay
OneFineDay

Reputation: 9024

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))

Upvotes: 15

Related Questions