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
Answer: Yes. Java can have an array of objects just like how it can have an array of primitive types.
Use the Object. values() method to convert an object to an array of objects, e.g. const arr = Object. values(obj) .
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.
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))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With