Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 832
Dany Avatar asked May 23 '13 22:05

Dany


People also ask

Can you create an array of objects?

Answer: Yes. Java can have an array of objects just like how it can have an array of primitive types.

How do you make an object array of objects?

Use the Object. values() method to convert an object to an array of objects, e.g. const arr = Object. values(obj) .

How arrays are created in VB net?

We can declare an array by specifying the data of the elements followed by parentheses () in the VB.NET. In the above declaration, array_name is the name of an array, and the Data_Type represents the type of element (Integer, char, String, Decimal) that will to store contiguous data elements in the VB.NET array.


2 Answers

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))
like image 100
OneFineDay Avatar answered Sep 29 '22 08:09

OneFineDay


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))
like image 36
Adrian Avatar answered Sep 29 '22 08:09

Adrian