Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

What is the best way to structure this class

Discussion in 'Scripting' started by aubergine, Feb 26, 2011.

  1. aubergine

    aubergine

    Joined:
    Sep 12, 2009
    Posts:
    2,878
    Probably a very simple question but i lost it at this point.

    I have a class like follows:

    public class Person {
    public string name;
    public List<Person> children = new List<Person>();
    }

    when i instance this class, it creates 1 person and few children then few more children for the previous children then..etc.

    I dont want that, i want children list to be instanced once. So do i have to seperate children list or is there any other way?
     
  2. Cameron_SM

    Cameron_SM

    Joined:
    Jun 1, 2009
    Posts:
    915
    public static List<Person> children = new List<Person>();

    Static means the field belongs to the Class, not every instance of that class.

    You can then access Person.children[...] from anywhere in any other script or just children[...] from within an instance of a Person class and they will all point to a single List.
     
  3. aubergine

    aubergine

    Joined:
    Sep 12, 2009
    Posts:
    2,878
    I meant i want a children list for every person but i dont want a children list for every persons children.
    If i make it a static then wouldnt it mean theres 1 child list at all?

    Anyways i made a childperson class to wrap things up. and it does the job.
     
  4. Antitheory

    Antitheory

    Joined:
    Nov 14, 2010
    Posts:
    549
    I would make a class Person that contains everything common to your Persons. Then I would make classes "Parent" and "Child" derived from Person.
     
  5. Cameron_SM

    Cameron_SM

    Joined:
    Jun 1, 2009
    Posts:
    915
    Arr I see.

    Technically, this shouldn't be an issue as long as your constructor/awake/start code does not create more person instances.

    Generally with this kind of a structure you build/populate it from an external class/script so you don't have people creating other people all willy nilly (like the 70s).

    Having empty List<Person>'s won't really cause any issues. The other options is to create a "soft collection" where you have public pointers to other Persons:

    public Person parent = null;
    public Person firstChild = null;
    public Person nextChild = null;

    As long as your code reinforces these references then all should be fine. public properties with custom get/set code works wonders here, you can also implement array access [...] on top of all this, but that's kinda overkill IMO, may as well just use a list.
     
    Last edited: Feb 26, 2011