C# List advice request

Hi everyone,

I want to create a scriptable object that will hold a list of variables that can be accessed from other scripts.

What I want to do is save multiple variables per list item as I want to keep them grouped together as there will probably be many entry’s which may get confusing.

e.g.

Name, Color, Color Code

Is this the right way to do this?

List<MyList> myList = new List<MyList>(Name, Color, Color Code);

If it is… is this the way to add a new list item?

myList.Add( new MyList(Name, Color, Color Code));

You should create addiotional class for storing your data structure in one item

/// Item
class MyListItem
{
   public string Name {get;set;}
   public Color Color {get;set;}
   public int ColorCode {get;set;}

   public MyListItem(string name , color Color, int colorCode)
   {
     Name = name;
     Color = color;
     ColorCode = colorCode;
   }
}

Usage:

/// create new collection
List<MyListItem> myList = new List<MyListItem>();

/// populate collection with new items
myList.Add( new MyListItem("Name", Color.red, 1));
myList.Add( new MyListItem("Name1", Color.green, 2));
2 Likes

Thanks Patico. Thats a huge help

Also should the class be:

class MyListItem : ScriptableObject ?

No, in this case it just defines a structure of item in your list. But if you want to show/edit items in Inspector panel, you have to mark MyListItem class with Serializable attribute.

[Serializable]
class MyListItem
{
...
}

Thanks again for replying.

I may have gotten confused here but I think I need to use a scriptableObject as I am trying to create a very basic editor extension and the list will be used to hold the variables created in that editor window. Can this be done with a serializable object?

You should use Serializable attribute when you making object for editor, especially when you want to show object’s properties easy. I propose to use this case:

[Serializable]
public classs MyEdatableObject : ScriptableObject
{
   [SerializedField]
   List<MyListItem> myList = new List<MyListItem>();
   
   [Serializable]
   class MyListItem
   {
    public string Name {get;set;}
    public Color Color {get;set;}
    public int ColorCode {get;set;}
   
    public MyListItem(string name , color Color, int colorCode)
    {
      Name = name;
      Color = color;
      ColorCode = colorCode;
    }
   }
   
   
   void Start()
   {
     /// populate collection with new items
     myList.Add( new MyListItem("Name", Color.red, 1));
     myList.Add( new MyListItem("Name1", Color.green, 2));
     ...
   }
}

Thank you for your help. I really appreciate it. I’ll try that out now and then try and recreate it again.