Setting up dictionaries to handle player and enemy units

I’m a beginner/hobbyist dev working on a tactical dungeon crawler/RPG inspired by X-Com. I’ve completed my first “milestone” of being able to spawn and configure basic units with relevant stats / information. I want to start on my second milestone of getting a basic turn based combat system up and running.

The rough idea is to have a state machine script and in the first state call a script to spawn the units for that dungeon. Currently I do this by instantiating prefabs that have a script component that builds each unit with some randomisation. This is where I hit my first hurdle: How to go about referencing the units I’ve spawned… Obviously I need to add them to some sort of list, and based on previous advice I’ve gotten a dictionary sounds like the way to go but I’m unsure as how I should implement that.

I know I need a key and a value. Currently when I spawn/build a unit I’m giving it an ID derived from gameObject.GetInstanceID so I thought I’d use that as the key and GameObject as the value.

So first off, is there a common/standard way of handling this that I should know about? If not the main questions I’ve got are:

  • Is there a better / more sensible way of choosing a key for my units?
  • Is gameobject the best thing to use for the value?
  • Where would you normally declare / store the dictionary?
  • Should I add each unit to the dictionary immediately after spawning it, or do some kind of search once all the units have spawned?

I know that’s a lot of questions, but any answers or general advice would be appreciated. Thanks!

I think you’re looking for a reference to your instantiated objects. From there you can reference scripts on that object. For simple stuff I use an array. Instead of instantiating as GameObject, use GameObject[ ]. Make your array public or private as you need.

You may also want to look into object pooling, which is much more efficient if you’re instantiating and destroying a lot.