Search Unity

Scriptable Object, simplest use.

Discussion in 'Scripting' started by runonthespot, Mar 23, 2013.

  1. runonthespot

    runonthespot

    Joined:
    Sep 29, 2010
    Posts:
    305
    Hi all,

    Just wanted to post this- was playing around this evening with ScriptableObject. This uses the ScriptableObjectUtility from the wiki, and is the simplest example for myself I could possible devise.

    Take a look at the "simple" scene, the DescribeLevel script shows you how to use "Levels" created. The levels themselves are just a basic serialised class with a couple of variables. If you go to the project tab of Unity and create a new object, you'll see "Level" is a new type.

    The basic idea is any class that derives from ScriptableObject can be setup in this way, to create little ".asset" files that can have things stored in them. Unity handles all the serialization. These can then be linked via public references or loaded via Resources.Load (both ways are illustrated in the DescribeLevel.cs)

    Hope you all find this as useful as I have.
    Mike
    @runonthespot

    View attachment $SimplestScriptableObject.unitypackage
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Good stuff. As someone who doesn't do a terrible amount of Editor customization (only because the current project doesn't call for it) things like this are very helpful.

    Do you think this might be an overlooked method of storing things like configuration settings that a developer can change via the Editor interface? Thinking out loud because we recently got to the point where multiple people are touching the same Unity project via Mercurial so individual config settings that are easy to set up would be nice (most of the others don't have much experience with Unity).
     
  3. runonthespot

    runonthespot

    Joined:
    Sep 29, 2010
    Posts:
    305
    Yeah, I'd say that sort of thing is exactly what this is for.

    If you have assetserver they'd be version controlled too. I got the idea of investigating this more after looking at the assets that Smooth Moves was creating ("BoneAnimations" etc).

    In my case, level configurations for my cube popping game fit in here nicely, covering things like dimensions, probabilities of certain things appearing etc.

    The best thing is that these things are nestable (even in Unity3.5) so for example, I created something called "Palette" which was just a string description and a List of colors, Created a few Palette assets and then my level configuration asset just has a public reference to a Palette. 10 levels share the same palette asset. In code, Level.Palette.ColorSet gets me the colors It all works so nicely that I'm surprised it isn't more detailed in the Unity docs.

    Otherwise ScriptableObjects work just like gameobjects/prefabs in that you can create your own editors for them etc.