1

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.

1
  • 1
    You are on the right track. The trick here is that as soon as you start thinking "Dynamically named variables" instead think "Arrays" or "Collections". You can have an array of your NPC objects or a collection of your NPC objects. See here for a similar question Personally I would prefer a collection here since it's a little more versatile than an array, although an array would suffice. Commented Apr 6, 2018 at 20:49

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Elegant! Much appreciated!

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.