Search Unity

Create lists from ScriptObject using a generic method

Discussion in 'Scripting' started by gareth_untether, Dec 15, 2019.

  1. gareth_untether

    gareth_untether

    Joined:
    Jan 5, 2018
    Posts:
    69
    I need to make a generic method in C# that builds a list from items in my ScriptableObject.

    Below is a screen shot of the SO in the inspector. The SO is made from a spreadsheet using QuickSheet.

    I want to be able to take any SO that is in the same category (has the same row names ID, State, En, Es, but different values) and extract each element ID, State, etc. to its own list.


    upload_2019-12-15_16-42-27.png
     
  2. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    @tik_tikkers

    How does this relate to Scriptable Objects?

    "I want to be able to take any SO that is in the same category"

    I don't see any categories for Scriptable Object, only fields of list items?

    To me it seems your list is just a list in SO with typical C# classes. You could probably use Linq or Find method of List.
     
  3. gareth_untether

    gareth_untether

    Joined:
    Jan 5, 2018
    Posts:
    69
    I still do not have a generic method, but I am a little closer.

    This is sudo code for what I would like:
    Code (CSharp):
    1.     private string ActionString(int id, string targetLanguage, object[] scriptableObjectArry)
    2.     {
    3.         // Search the scriptable objects elements to find the ID
    4.         // Search that element to find the targetLanguage string
    5.         // Return the string
    6.     }
    The code below allows me to search through the ScriptableObject and return what I need. However, the ScriptableObject is embedded in the code, for a new ScriptableObject I have to copy and paste then manually edit the ScriptableObject part of the code.

    Code (CSharp):
    1.     [SerializeField] AppleActions appleActions;                 // <--- ScriptableObject
    2.  
    3.     private string ActionString(int id, string targetLanguage)
    4.     {
    5.         List<AppleActionsData> items = new List<AppleActionsData>();        // 1 Make a list
    6.  
    7.         items.AddRange(appleActions.dataArray);     // 2 Add the SO data
    8.  
    9.         AppleActionsData foundID = items.Find(x => x.ID[0] == id);        // 4 Search for the ID and add it to a list
    10.  
    11.         var foundAction = foundID.GetType().GetProperty(targetLanguage).GetValue(foundID, null);     // 5 Get the language data from the element
    12.  
    13.         var strings = ((IEnumerable)foundAction).Cast<object>()                           // 6 Convert language data to a string array
    14.                                   .Select(x => x == null ? x : x.ToString())
    15.                                   .ToArray();
    16.  
    17.         string actionString = strings[0].ToString();
    18.  
    19.         return actionString;
    20.     }