Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Need advice on how to make list of variables

Discussion in 'Scripting' started by Zukas, Jan 27, 2017.

  1. Zukas

    Zukas

    Joined:
    Dec 17, 2013
    Posts:
    40
    To help catch idea of what I want to achieve, I'm making Map Editor for my game and it is going to contain Entities that players will be able to create. I want each Entity to be class, that has list of variables of various types (Color, Float, Bool, etc.) that would be easy to access, change, modify.

    I've thought of making generic interface or generic class, but then I wouldn't be able to make one unified List<I> and would cause big spaghetti code with lots of conditionals for each different type of list.

    I already know that I'll need to have a lot of conditionals just to check variable type and draw it in UI.

    It would be great if it would also easily serialize the List/Array of variables using XmlSerializer.
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
  3. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Sure you could. That's exactly what doing it would buy you :)

    Honestly - I'd invert the relationship. Let each type be responsible for drawing its UI.
    Code (csharp):
    1.  
    2. public interface EntityDrawer
    3. {
    4.     void Draw();
    5. }
    6.  
    7. List<EntityDrawer> entities;
    8.  
    9. foreach (var entity in entities)
    10. {
    11.     entity.Draw();
    12. }
    13.  
    Or if you'll never have an Entity that doesn't need a UI then just put Draw on the abstract Entity base class.

    If you don't want the UI logic in the object itself then I'd build a Dictionary of types to delegates that do the drawing. Then just look up what delegate to execute by what type of entity it is.

    Code (csharp):
    1.  
    2. Dictionary<Type, Action<Entity>> drawers;
    3.  
    4. if (drawers.TryGetValue(typeof(myEntity), out action)
    5. {
    6.     action(myEntity);
    7. }
    8.  
     
    Last edited: Jan 30, 2017
  4. Zukas

    Zukas

    Joined:
    Dec 17, 2013
    Posts:
    40
    I'll look into both ways and find the one most fitting to my situation, appreciate it!