ScriptableObject

本文介绍了一种在Unity中创建自定义资源文件的方法,通过继承ScriptableObject类并结合使用简单的工具类,可以轻松地管理和编辑游戏中的配置数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文


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.
通常贯穿游戏开发的过程中,你最终构建一些组件,需要通过一些配置文件获取数据。这可以为你的程序级别生成系统一些参数,也许是你的手势识别系统的一个手势集合,或者任意数量的东西。如果你正使用 UNITY 开发, 你可能开始这个任务是因为创建一个序列化类, 设计用来作为简单的保存你所需要的所有配置数据。

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.
但然后呢?你如何将数据转换到类中?你会创建一大堆 XML 或者 JSON 文件,并且在游戏开始时加载他们?也许你在需要该数据的类中有你数据类的公共实例,并且你在 inspector 进行所有设置,并且创建大量的 prefabs,每个对应不同种类的配置。

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.
那么在这片文章中,我会告诉你一个简单的方法将这些序列化数据容器类转换到自定义资源文件。这具有许多优于使用 XML 或者其他外部文件格式的好处。比如,一般情况下,你的文件大小会小很多,并且 UNITY 会处理所有的序列化和反序列化。

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.
我认为这样的事情最好通过一个列子来解释。所以我们假装我们正在试图创建一个 JRPG 类型的对话系统, 就和在 “Fire Emblem” 或者 “Harvest Moon” 和其他 JRPGs 中看到一样。你知道这种类型。他们有一个大的文本泡泡,从下往上滑动显示,并且对话角色的头像在左边或者右边。

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.
上面我们用几个枚举来描述角色和屏幕位置,一个 texture 用于显示角色,一个 string 用于在对话泡泡中角色实际对话内容, 一个 GUIStyle 用于秒速字符串格式, 业余有一个 float 用于控制文本的显示速度,和一个 audio clip 用于对话泡泡播放。


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.
接下来我们创建用于所有的对话的类,并且它将仅仅保持一个 DialogueElement 对象的列表。但是不是简单的使他成为一个序列化类,而是使它继承于 ScriptableObject。你知道,这件事,你总是知道在那里,但是从来不知道为什么?这 ScriptableObject 类将给我们能将我们 dialogue class 转换到自定义资源文件的魔力。


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.
// http://jacobpennock.com/Files/CustomAssetUtility.cs http://www.jacobpennock.com/Blog/customassetutility-source/


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.
一旦你已经安装到自己的工程中,你能将 dialog class 或者 任意继承 ScriptableObject 的类 转换到一个自定义的资源文件中,超级简单的使用几行代码。

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:
仅仅创建一个新的类/文件名字为 DialogueAsset.cs,并且确定他在一个 Editor 文件夹中。然后在该类中创建一个菜单项用于你新的资源,仅仅通过下载的工具类调用 CreateAsset,如下:


using UnityEngine;
using UnityEditor;
using System;


public class DialogueAsest
{
[MenuItem("Assets/Create/Dialogue")]
public static void CreateAsset ()
{
ScriptableObjectUtility.CreateAsset<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.
当你点击新创建的资源文件时,在 inspector 中将显示你的 DialogueElements 列表和他们所有的公有变量。就如你创建了一个 DialogueElement 的实例在 MonoBehavior 里面。但是不像实例化 DialogueElements,因为这些在他们自己的资源文件中, 你对他们做的所有改变将始终保持不管在编辑时和运行时。所以如果你在游戏运行时做了一些改变在预览模式,这些改变将保持即使你停止运行游戏。同样的技术基本上是GUISkin 和 UNITY的其他内置的资源是一样的。

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.
现在,在另一个类中访问数据,该类你写来实际显示对话在屏幕上,仅仅使用一个 dialogue 的公共实例。

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.
然后仅仅通过 inspector 赋值。或者通过点击小圆圈并且从弹出的的列表中选择他或者仅仅拖拽一个新的资源文件到开口曹中。

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:
如果你觉得雄心勃勃,或者 仅仅想才去额外的步骤,你可以去写一个自定义的 inspector 类来配置你的资源文件在 inspector view 如何显示。如果这样,你将要创建一个新的 class/file 并且称为 DialogueEditor.cs, 并却表他也是被放置在 Editor 文件夹中。然后你将想编辑该类如下:


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.
然后在 OnInspectorGUI 函数中填补所有的代码来显示你希望编辑你资源的选项。这能很好的清理和简化 inspector view 中的显示,或者隐藏你不想要编辑的选项。这也很利于团队工作。他真的很方便让团队成员更容易理解,。仅仅点击创建的 dialogue 并且补充所有的内容。这儿有一个截图显示你能做什么使用创建一个自定义 inspector 对于这个列子的 dialogue 类,


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:
但是这有有又一个小小的警告。如果你写了一个自定义的 inspector 类用于编辑你的资源文件,或者如果你在另外一个 MonoBehavior 在运行时间改变了自定义的资源文件的任意值。你需要调用 Unity’s 的 SetDirty 方法来设置你改变的资源对象,像这样:


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.
这是为了让 UNITY 知道该对象的内容已经改变,并且需要重新序列化和保存到硬盘。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值