Search Unity

Scriptable Objects

Discussion in 'Scripting' started by Disaster, Dec 29, 2011.

  1. Disaster

    Disaster

    Joined:
    Oct 31, 2009
    Posts:
    43
    I've recently discovered Scriptable Objects and have been frantically searching the forums, answers and the internet to try and learn more about them. It's a shame they are not documented better because they seem incredibly useful and I think they are exactly what I need for my current game.

    What I am trying to do is create a list of "item" objects, populate them into a list and edit them via either an editor window or the inspector. So, an example object might look something like this:

    Code (csharp):
    1. [System.Serializable]
    2. public class SomeObject{
    3.      public float x = 0f;
    4.      public float y = 0f;
    5. }
    What I want to be able to do is add, edit and remove "SomeObjects" in a list via the inspector and reference them throughout my code. For example, some pseudo code:

    Code (csharp):
    1. for each(SomeObject someObject in SomeObjectManager.objectList){
    2.      Debug.Log(someObject.x);
    3. }
    The beauty of using ScriptableObjects here is that this list will never change at runtime and be consistent throughout each of my scenes, so storing the data in a .asset file is really handy for me in this instance. If you consider collectible items in an RPG game for example, ScriptableObjects are a good fit for that, right?

    If anyone could tell me if a) ScriptableObjects are indeed a good fit for what I am trying to do and b) any information / code snippets I could use to help accomplish my goals I would be very grateful. I am going to update this post with as much code and info as I can so anyone else struggling with the lack of documentation might find it useful. Thanks!
     
  2. andorov

    andorov

    Joined:
    Feb 10, 2011
    Posts:
    1,061
    ScriptableObjects are great. I too recently discovered them and moved large swaths of my project to utilize them. I use them for about the same stuff that you are trying to accomplish. Actually, in my signature you can take a look at Tutorial #6 where I create some basic items to use in my engine with scriptable objects.

    I take the concept of scriptable objects one step further and use them as containers for both logic (ie, custom code) and serializable data!

    One thing to be careful about is that scriptable objects are persistent "assets" and that you should /generally/ avoid modifying fields at runtime, unless you have excellent procedures in place to handle diverging assets derrived from the root asset. The in-built material system, for example, transparently creates new materials when settings diverge.