Search Unity

How to add a Scriptable Object to an List

Discussion in 'Scripting' started by sebhah, Sep 28, 2020.

  1. sebhah

    sebhah

    Joined:
    Jan 6, 2019
    Posts:
    26
    Hello,

    I have a question. I made a Power Up system that allows you to drive over a Power Up and get you a specific power-up. But now I want you to get a random power up. Each power up is a Scriptable object. So it seems to me the easiest to put all Scriptable objects in a List and then extract a random Scriptable Object from it. I just have no idea how to add a Scriptable Object to a List. Can someone help me with this?

    So the question is. How can I add Scriptable objects to an List?

    Thank you in advance.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Just like any other C# object!

    Code (csharp):
    1. MyList.Add( eachPowerupInstance);
    What might be more useful to you however, in a Unity context, is to put all your powerup scriptable object assets in a
    MyPowerupDirectory
    directory, and then load them with
    Resources.LoadAll<Powerup>();


    Code (csharp):
    1. Powerup[] AllPowerups = Resources.LoadAll<Powerup>( "MyPowerupDirectory/");
    I use this pattern ALL over the place: weapons, powerups, game modes, etc. all the uses I find for ScriptableObjects.

    You don't get a list back but rather an array. But if you need a List, you can easily create one by using the array loaded above to initialize a list:

    Code (csharp):
    1. List<Powerup> PowerupList = new List<Powerup>( AllPowerups);
    To control the order of the array, you can sort it however you like with
    System.Array.Sort()