2. 创建配置编辑器
在本小节中,我们为上一节定义的 GameConfig 创建对应的编辑器。
我们创建名为 GameConfigEditor 的编辑器类,并从winS.UnityEditor.ConfigManagement.ConfigEditor继承:
CharacterConfigEditor.cs
using winS.UnityEditor.ConfigManagement;
public class GameConfigEditor : ConfigEditor<GameConfig>
{
protected override string configPath { get; }
protected override void OnEditorCreated()
{
throw new System.NotImplementedException();
}
}
通过上述代码可以看到,winS.UnityEditor.ConfigManagement.ConfigEditor要求子类实现:
- configPath:表明配置文件所在路径(基于项目目录)。
- OnEditorCreated:当编辑器被打开时调用,您可在此回调内创建配置文件的GUI。
我们简单实现此编辑器,代码如下:
CharacterConfigEditor.cs
using UnityEditor;
using winS.UnityEditor.ConfigManagement;
using winS.UnityEditor.GUI;
public sealed class GameConfigEditor : ConfigEditor<GameConfig>
{
protected override string configPath => "Assets/Configs/GameConfig.txt";
[MenuItem("Example/Window/Game Config Editor")]
private static void Open()
{
GetWindow<GameConfigEditor>("Game Config Editor");
}
protected override void OnEditorCreated()
{
GUIUtility.factory.SetLabelWidth(120f);
Add(GUIUtility.factory.CreateTextField("Game name", config.name, newValue => config.name = newValue));
Add(GUIUtility.factory.CreateTextField("Game version", config.version, newValue => config.version = newValue));
Add(GUIUtility.factory.CreateIntField("Target FPS", config.targetFPS, newValue => config.targetFPS = newValue));
Add(GUIUtility.factory.CreateToggle("Run in background", config.runInBackground, newValue => config.runInBackground = newValue));
GUIUtility.factory.ResetLabelWidth();
}
}
在上述代码中,我们通过configPath属性将配置文件保存在路径 "Assets/Configs/GameConfig.txt" 下。
在OnEditorCreated方法中,我们借助winS.UnityEditor.GUI
扩展包的API来绘制对应的编辑器GUI。
同时,我们定义了一个静态方法Open并为其指定UnityEditor.MenuItem特性。 这使得我们可以通过菜单项 "Example/Window/Game Config Editor" 来打开编辑器。