Unity Pro Tip: Use custom made assets as configuration files

Often times throughout the course of developing a game you end up building some components that need to take in some data through some sort of a configuration file. This could be some parameters for your procedural level generation system, maybe a gesture set for your gesture recognition system, or really any number of things. If you’re developing inside of Unity you probably start this task off by creating a serializable class that is designed as a simple container to hold all the configuration data you are going to need.

But then what? How are you actually going to get your data into that class? Do you create a bunch of XML or JSON files and load them in when the game starts? Maybe you have a public instance of your data class inside of the class that needs the data, and you’re setting everything through the inspector, and then creating a ton of prefabs, one for each of the various configurations.

Well in this post I’m going to show you a simple way to turn those serializable data container classes into custom asset files. This has a number of benefits over using XML or some other external file format. For instance, in general, your file sizes will be much smaller and Unity will handle all the serializing and deserializing for you.

I think this sort of thing is best explained through an example. So I’m going to pretend we’re trying to build a JRPG type dialogue system, like those seen in “Fire Emblem” or “Harvest Moon” and hordes of other JRPGs. You know the type. They have a big text bubble that slides up from the bottom and then a flat picture of the character speaking either on the left or right.

Okay let’s start with creating our simple serializable data container for each individual dialogue speech element as so:

 [System.Serializable]
 public class DialogueElement
 {
     public enum Characters{ David, Megan};
     public enum AvatarPos{ left, right};
     public Characters Character;
     public AvatarPos CharacterPosition;
     public Texture2D CharacterPic;
     public string DialogueText;
     public GUIStyle DialogueTextStyle;
     public float TextPlayBackSpeed;
     public AudioClip PlayBackSoundFile;
 }

 
Above we have a couple of enums to describe what characters and screen positions are available, a texture that will be used for displaying the character, a string for what the character is actually saying in the speech bubble, a GUIStyle to style that string with, and maybe a float that we will use later to control how fast the text is displayed back, and an audio clip so we can play back a sound for each speech bubble.

Remember this is just an example so you could use the same techniques for any type of data container like the one above.

Next let’s create our class for a whole dialogue and it will just hold a list of those DialogueElement objects. But instead of making it a plain serializable class we will let it inherit from ScriptableObject. You know, that thing that you always knew was there but were never really sure why? The ScriptableObject class will give us the magic of being able to turn our dialogue class into our own custom asset files.

public class Dialogue: ScriptableObject
{
    public List DialogItems;
}

Now to be able to make custom dialogue assets from that dialog class, you need to download this CustomAssetUtility class and save it somewhere in your project folder. You can download it from this link (right click save as), or if you want you can copy and paste the source from here.

Once you have that installed in your project you can turn that dialog class or any of your classes that inherit from ScriptableObject into a custom assets super easily with just a couple lines.

Just make a new class/file called DialogueAsset.cs and make sure it’s inside an Editor folder. Then inside that class create a menu item for your new asset that just calls CreateAsset from the downloaded utility class like so:

using UnityEngine;
using UnityEditor;
using System;

public class DialogueAsest
{
    [MenuItem("Assets/Create/Dialogue")]
    public static void CreateAsset ()
    {
        ScriptableObjectUtility.CreateAsset<Dialogue>();
    }
}

Now when you go to Assets -> Create in the menubar or click the create button in your project view you’ll see an option to create a new dialogue.

And when you click on the newly created asset file the inspector view will show your list of DialogueElements and all their public variables. Just like it would’ve if you had created an instance of DialogueElement inside of a MonoBehavior. But unlike instanced DialogueElements, since these are in their own asset file any changes you make to them will remain persistent throughout edit time and runtime. So if you change some of the values here while the game is running in preview mode the changes will stay even after you stop running the game. This same technique is essentially how GUISkin and a number of Unity’s other built-in assets work.

Now to get access to the data from within another class, say the class you’re writing to actually display the dialogue on-screen, just make a public instance of the dialogue.

public class DialogWindow : MonoBehaviour
{
    public Dialogue DialogueFile;

    //The rest of your awesome code to playback
    //your dialogues or use your customs assets
    .
    .
    .

Then just assign it through the inspector. Either by clicking the little circle and selecting it from the list that comes up or just dragging and dropping one of your newly created asset files in the open slot.

If you’re feeling ambitious, or just want to take the extra step you can go on to write a custom inspector class to configure how your assets are going to be displayed within the inspector view. If so, you’re going to want to create a new class/file and call it something like DialogueEditor.cs and make sure it is also placed within an Editor folder. Then you’ll want to start off writing that class with something like this:

using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(Dialogue))]
public class DialogueEditor : Editor
{
    private Dialogue D; //Make an easy shortcut to the Dialogue your editing
    void Awake()
    {
        D=(Dialogue)target;
    }

    public override void OnInspectorGUI()
    {

    //The rest of your awesome code to allow custom editing
    // of your dialogues or other customs assets you make
    .
    .
    .

Then fill in the OnInspectorGUI function with all the code to display the options for the editing your asset that you want. This can be great for cleaning up and simplifying what is displayed in the inspector view, or hiding away options that you don’t want edited. It’s also great for working on teams. It’s really nice to be able to go to your less techno-savvy team members, the script writer for instance, and say “Look it’s really easy. Just click create dialogue and fill everything in.” Here’s a screenshot of what you could do with creating a custom inspector for this example dialogue class.

Oh but there is one small caveat. If you do write a custom inspector class for editing your asset files, or if you change any of the values within one of your custom assets from another MonoBehavior during runtime. You will need to call Unity’s SetDirty method on the object that you changed like so:

EditorUtility.SetDirty(yourInstanceOfACustomAsset);

This is so that Unity will know that the contents of the object have been changed and needs to be re-serialized and saved to disk.

So there you have it. How to make your own custom assets and use them as configuration files.

If you found this tutorial helpful please let me know in the comments, and as always you can stay updated with all my tutorials and plug-ins by following me on twitter.

About The Author

15 Comments

  1. Jacob says:

    I’m sorry that I did not include the full source of my implementation of the custom OnInspectorGUI method. This is for three reasons. For one, I made it just as an example and it’s not really finished, notice a lot of the options are blank or just placeholders. For two, this tutorial is really more about how to create your own custom assets and not about how to write inspector GUIs. Thirdly, I think I may want to finish this example and make it into a complete solution for creating JRPG dialogs and submit it to the asset store. If you think that’s a good idea and would be interested in buying such a solution for maybe a couple dollars please let me know in the comments.

  2. Spencer says:

    Hi there, thanks for the tutorial. I get the feeling it’s the only one on the net regarding the ScriptableObjects, like this. I caught up with you in IRC and you said this approach could be used for something like keeping track of weapon instantiation information.

    I’ve followed the instructions and gotten it working up through the Assets –> Create –> Dialogue step. However, I’m still not understanding fully how I can utilize this for storing weapon parameters, and how to then access them. Could you provide any guidance?

    Cheers!

    [WORDPRESS HASHCASH] The poster sent us ’0 which is not a hashcash value.

  3. Chris says:

    Jacob, this is an excellent write up ! thank you. I would be curious to see how you implemented the custom look of the foldouts.

    I have a couple questions:
    * do assets created with this method need to exist in /Resources folder, or is that not necessary?
    * I would like to see an example of interaction between this inspector and a custom EditorWindow.

    -chris

  4. michael says:

    Nice! I first saw this in the Scalable Gamedev video from Schell games but you put it all together in a complete package.

  5. Gordon says:

    This is awesome, thanks! You’re totally right – I’ve always seen ScriptableObject but never known what it was for. I’m going to go do this to define tutorial sequences right now. :)

  6. Cleophus says:

    Great tutorial! Now I understand ScriptableObjects.
    I think this project could be good enough for the asset store.

  7. Shawn Halwes says:

    Thanks for this! Unity’s docs are so vague on this and your post really connects the dots for me saving me a lot of time. :o)

  8. Me says:

    I get this error:
    The type arguments for method `CustomAssetUtility.CreateAsset()’ cannot be inferred from the usage. Try specifying the type arguments explicitly

    how to solve this?

    • Jacob says:

      Sorry you have to put the type of the object in angle brackets. Looks like there was a problem with the last wordpress upgrade and all the code snippets with angle brackets were no longer formatted correctly. Its fixed now, you’ll find the correct code above.

      Thanks for catching this.

  9. Lucas says:

    Loved your tutorial! Thanks for the help, I ‘m finishing on making my own AI State Machine System, and needed a way to make my editor inside Unity. Thanks!

  10. Luis Fonseca says:

    Hey Jacob,

    Thanks for your awesome tutorial! Definitely the best resource on the subject I could find.

    However, I’m getting a strange issue where some times (can’t precise when or how) my custom assets loose their data and go back to a previous state (not default values, but apparently an older version). Do you have any idea on what that might be?

    Totally lost here and would appreciate any hint! Thanks!

    • Luis Fonseca says:

      I’ve pinpointed the problem to having a custom editor. Like you say in your article, if we use a custom editor we need to use that “SetDirty” trick, but I have no idea where to put that. Can you please clarify?

  11. Jacob,

    Thanks for writing this up! It really helped me fill a gap in Unity.

  12. Awesome tutorial. I never really knew how to do this, this helped me a lot!

    Cheers!

  13. Korontari says:

    Thank you for the tutorial. It really helped me grab custom asset creation. And that little EditorUtility.SetDirty function was exactly my problem solver. Thanks!

Leave A Reply