Search Unity

Is it smart to store all units in a list for a RTS game?

Discussion in 'Scripting' started by RedSC, Jul 4, 2015.

  1. RedSC

    RedSC

    Joined:
    Jul 4, 2015
    Posts:
    2
    Hi,
    I'm developing a RTS game with unity and I'd like to store all the units in a list, however I'm not sure if that is a good idea. I've put together a script to initially populate the units list and then methods to add and remove units form the list. The problem is that I should add and remove the units every time one is spawned or destroyed in the scene. I'm afraid that this would end up using more resources than search for the objects every time I need them and its recurrent GetComponent.

    I also considered to use a singleton pattern. Does any of this make any sense to you?
     
  2. lordconstant

    lordconstant

    Joined:
    Jul 4, 2013
    Posts:
    389
    If you store them in a quadtree or an octtree then you can do checks faster i believe.
     
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    A list is great for ordered sets. If you need to access items by index then use a list. But if you just want a way to iteterat across all units quickly, then a HashSet might be better. HashSets tend to have faster add and remove times too.

    As always, profile first before going on vague advice on the net.

    It's also useful to hide the implementation of a collection from the rest of your code. That way if you change your mind later, there is not a huge amount of code to rewrite.
     
  4. Crayz

    Crayz

    Joined:
    Mar 17, 2014
    Posts:
    193
    A singleton is also fine for what you're doing, you'll be able to set up a single instance that is available anywhere rather then having to find the reference to your list of units every time you want to do something with it (which will be often)

    This is actually exactly what I'm doing for my RTS. Singleton entity manager, whenever a unit spawns it registers itself into the manager which adds the entity to a list and gives it a unique identifier. One of the big uses I have (off the top of my head) for this is for box selecting units, I'm able to iterate through the entity list and check if any entities world positions are within the rect of the box select.
     
  5. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Be cautious with singletons. They often end up creating as many issues as they solve.
     
  6. RedSC

    RedSC

    Joined:
    Jul 4, 2015
    Posts:
    2
    Seems that we are use having the same headaches. I like your idea of aiding unique identifiers I'll implement it to my project.

    I'll try your suggestions, thanks. I'll probably end up not using the Singleton, last time I used one was a nightmare.
     
  7. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    I opted for a mix of Dictionary and Array usage.