十一:连连看插件实践
11.1 基础知识
需要的技术前提
- 掌握Unity最老的GUI技术,也就是将代码写在OnGUI里面。
- 使用EditorGUILayout,GUILayout进行布局
- 使用AssetDatabase进行编辑器资源加载
- Asseet窗口创建GUISkin,将练练看的元素按照1---n进行命名(自己的规则,自己匹配即可)
- 设计界面如下所示:上面是棋盘,下面是当前选中的按钮。点击确定的时候,将二维数组存储到一个txt文件之内即可。
- 最终效果如图:存储二维数组到Resources目录下的LevelInfo目录下的文本文件,方便后期动态加载关卡。
具体代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Text;
using System.IO;
public class WindowExample2 : EditorWindow
{
#region 窗口需要使用的变量
public GUISkin skin;//皮肤
public int currentIndex;//当前点击的下标
public int[,] map = new int[5, 5];//二维数组
#endregion
private static WindowExample2 window;//窗体实例
//显示窗体
[MenuItem("MyWindow/Second Window")]
private static void ShowWindow()
{
window = GetWindow<WindowExample2>("Window Example");
window.Show();
window.maxSize = new Vector2(400,500);
}
private void OnEnable()
{
//加载GUISkin
skin = AssetDatabase.LoadAssetAtPath<GUISkin>("Assets/skin.guiskin");
}
//绘制窗体内容
private void OnGUI()
{
/*
EditorGUILayout.BeginVertical("box");
EditorGUILayout.LabelField("Your Second Window", EditorStyles.boldLabel);
GUILayout.Label(new GUIContent("MyLaabel"));
GUILayout.Space(20);
GUILayout.TextField("对象名称");
name = EditorGUILayout.TextField("StringValue", name);
if (GUILayout.Button(new GUIContent("确定"), GUILayout.ExpandWidth(true)))
{
Debug.Log("Clcik");
}
EditorGUILayout.EndVertical();
*/
GUI.skin = skin;
for (int i = 0; i < 4; i++)
{
if (GUI.Button(new Rect(i * 50, 300, 50, 50), "",
skin.GetStyle((i + 1).ToString())))
{
ChangeIndex(i + 1);
}
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
//0是style里面的默认图片
if (GUI.Button(new Rect(j * 50, i * 50, 50, 50), "", skin.GetStyle("0")))
{
MapClick(i * 5 + j);
}
}
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
GUI.Button(new Rect(j * 50, i * 50, 50, 50), "",
map[i, j].ToString());
}
}
if (GUI.Button(new Rect(0, 350, 200, 30), "确定"))
{
Debug.Log("自己保存在指定的路径");
SaveToFile();
}
}
private void SaveToFile() {
//如何将一个二维数组写入到文件里面
StringBuilder buider = new StringBuilder();
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
buider.Append(map[i, j]).Append(",");
}
//删除每一行的逗号
buider.Remove(buider.Length - 1, 1);
//追加换行
buider.Append("\n");
}
//删除最后一个换行
buider.Remove(buider.Length - 1, 1);
string dir = "Assets/Resources/LevelInfo";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
FileStream stream = File.Create(dir + "/01.txt");
//将字符串写入到文件之中
byte[] content = System.Text.Encoding.UTF8.GetBytes(buider.ToString());
stream.Write(content, 0, content.Length);
stream.Close();
AssetDatabase.SaveAssets(); //保存
AssetDatabase.Refresh();//刷新
}
//修改当前物体下标
private void ChangeIndex(int tag)
{
currentIndex = tag;
}
//点击修改对应的二维数组元素
private void MapClick(int tag)
{
map[tag / 5, tag % 5] = currentIndex;
}
}
(8)这里只是演示了一个基本的界面,比较丑陋,大家自己进行扩展即可。点击菜单栏的Window--SecondWindow即可查看自定义的工具窗口