这篇的主要内容为如何通过编辑器窗口(EditorWindow)实现简单呃技能编辑功能。大致思想为在窗口中输入内容并且保存为可以使用的配置文件。
Unity需要下载NewtonSoftJson插件。
首先创建文件夹:Resources(资源)和Editor(编辑器)
生成空物体并挂上脚本Game,在脚本立会生成信息类Info
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Game : MonoBehaviour
{
// Start is called before the first frame update\
Info info;
GameObject go;
private void Awake()//读取文件并且反序列化
{
info = JsonConvert.DeserializeObject<Info>(Resources.Load<TextAsset>("3").text);
}
void Start()//根据id决定生成的游戏对象
{
if (info.id == 0)
{
go = GameObject.CreatePrimitive(PrimitiveType.Cube);
}
else if (info.id == 1)
{
go = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
}
else if (info.id == 2)
{
go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
}
go.transform.position = new Vector3(info.x, info.y, info.z);
}
}
public class Info //声明类
{
public int id;//id
//Json不能直接转换Vector3,所以用x,y,z代替,在生成时再转换
public float x;
public float y;
public float z;
}
在Editor文件夹下添加脚本Editor
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using Newtonsoft.Json;
using System.IO;
public class Editor : EditorWindow
{
Info info = new Info();
List<string> list = new List<string>()
{
"立方体","圆柱体","球体"
};
Vector3 pos;
int index = 0;
[MenuItem("Tool/Editor")]
public static void Init()
{
Editor edi = GetWindow<Editor>("Editor");
if (edi != null)
{
edi.Show();
}
}
private void OnGUI()
{
GUILayout.BeginHorizontal();
index = EditorGUILayout.Popup(index, list.ToArray());
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
pos = EditorGUILayout.Vector3Field("位置", pos);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (GUILayout.Button("保存"))
{
info.id = index;
info.x = pos.x;
info.y = pos.y;
info.z = pos.z;
string str = JsonConvert.SerializeObject(info);
File.WriteAllText(Application.dataPath + "/Resources/3.json", str);
Debug.Log("保存成功");
}
GUILayout.EndHorizontal();
}
}
注:有 GUILayout.BeginHorizontal() 就一定要有 GUILayout.EndHorizontal()来结尾
效果:
点击Editor,在窗口内输入属性然后点击按钮保存
运行程序,生成游戏对象。如果Resources文件夹为空,刷新(ctrl+r)即可