user9609468
user9609468

Reputation: 11

Multiple instances of an object/class

I'm making a simple game in VBA excel that's like Rogue or Nethack. It takes place in a gui window. I've got an array to hold the playing field etc. and a class for the player, which has their coordinates stored and some subs to move around etc.

I then created an NPC class that moves around at random. I declared it the usual way, Dim NPC as NPCclass (inside the declarations) and then Set NPC = New NPCclass (inside a sub, which seems to be necessary but none of the tutorials mention that?) So far so good, the NPC is represented by an ASCII character and does what I want it to.

However, now I want to create more NPCs after intervals of a few turns. But I can't figure out how to do it. It seems like for every additional instance of my NPC, I have to do another Dim NPCxyz as NPCclass.

So I tried to generate a string, say "npc_name" that holds the name of the next NPC to be generated, as in NPC1 or NPC2 and so on. Unsurprisingly, if I then try Dim npc_name As NPCclass VBA doesn't understand that I want to create another instance of NPCclass with the string inside npc_name as its name. Instead it thinks I want to declare npc_name again, like when I said Dim npc_name As String earlier.

How can I create more NPCs that use the same class but move independently around the array/playfield? I feel like I'm misunderstanding something obvious because none of the tutorials I looked at went into this.

Upvotes: 1

Views: 1065

Answers (2)

Marcelo Gazzola
Marcelo Gazzola

Reputation: 1083

You also can use collections:

Dim NPC as New NPCclass
Dim colNPC as New Collection

for i = 1 to 20
    colNPC.add New NPC
next

Upvotes: 2

Ricardo González
Ricardo González

Reputation: 1423

Just create an array of objects...

Dim NPC(1 to 20) as NPCclass

For i = 1 to 20
    Set NPC(i) = New NPCclass

    '... your object init ...
    NPC(i).SetSometing = 0
    NPC(i).DoSomething()
Next i

And if later on you want to increase the list you just need to do something like

ReDim Preserve NPC(50)

Upvotes: 2

Related Questions