Unity教程之-制作闪亮的星星Star(四):Unity Editor编辑器实现Undo

2023-10-25 11:59

本文主要是介绍Unity教程之-制作闪亮的星星Star(四):Unity Editor编辑器实现Undo,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

继续上篇文章《Unity教程之-制作闪亮的星星Star(三):给Star创建Unity Editor编辑器》,在Unity中没有一种简单的方法来支持Undo事件,但我们可以做到接近支持。在我们的案例中,我们可以检查ValidateCommand事件是否发生,来判断Undo操作。当前被选中的对象这个事件的目标,我们假设它被修改过。

What’s a ValidateCommand?

ValidateCommand is a type of GUI event, which indicates that some special action happened, like undo or redo. So why isn’t it called something like ExecuteCommand? Actually, that command type exists as well. While they have a slightly different meaning, in practice you use them for the exact same purpose. Unfortunately, depening on exactly where you’re checking and how you’re constructing your GUI, either one or the other event happens, but not both. Why this is so, I do not know.
So to be perfectly safe, you have to check for both command types. In this case, however, you can suffice with checking ValidateCommand.

using UnityEditor;
using UnityEngine;[CustomEditor(typeof(Star))]
public class StarInspector : Editor {private static GUIContentinsertContent = new GUIContent("+", "duplicate this point"),deleteContent = new GUIContent("-", "delete this point"),pointContent = GUIContent.none,teleportContent = new GUIContent("T");private static GUILayoutOptionbuttonWidth = GUILayout.MaxWidth(20f),colorWidth = GUILayout.MaxWidth(50f);private SerializedObject star;private SerializedPropertypoints,frequency,centerColor;private int teleportingElement;void OnEnable () { … }public override void OnInspectorGUI () {star.Update();GUILayout.Label("Points");for(int i = 0; i < points.arraySize; i++){EditorGUILayout.BeginHorizontal();SerializedProperty point = points.GetArrayElementAtIndex(i);EditorGUILayout.PropertyField(point.FindPropertyRelative("offset"), pointContent);EditorGUILayout.PropertyField(point.FindPropertyRelative("color"), pointContent, colorWidth);if(GUILayout.Button(teleportContent, EditorStyles.miniButtonLeft, buttonWidth)){if(teleportingElement >= 0){points.MoveArrayElement(teleportingElement, i);teleportingElement = -1;teleportContent.tooltip = "start teleporting this point";}else{teleportingElement = i;teleportContent.tooltip = "teleport here";}}if(GUILayout.Button(insertContent, EditorStyles.miniButtonMid, buttonWidth)){points.InsertArrayElementAtIndex(i);}if(GUILayout.Button(deleteContent, EditorStyles.miniButtonRight, buttonWidth)){points.DeleteArrayElementAtIndex(i);}EditorGUILayout.EndHorizontal();}if(teleportingElement >= 0){GUILayout.Label("teleporting point " + teleportingElement);}EditorGUILayout.PropertyField(frequency);EditorGUILayout.PropertyField(centerColor);if(star.ApplyModifiedProperties() ||(Event.current.type == EventType.ValidateCommand &&Event.current.commandName == "UndoRedoPerformed")){((Star)target).UpdateStar();}}
}

最后,一个舒服的编辑过程!还有什么需要做吗?在编辑器的右上角有一个齿轮图标能够重置组件。当我们重置Star组件的时候我们的Mesh没有及时更新。

你可以定义Reset方法来监听一个组件的重置。这事Unity为Editor及其子类提供的一个方法。当这个事件发生,我们只要及时更新我们的星星就可以了。

using System;
using UnityEngine;[ExecuteInEditMode, RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Star : MonoBehaviour {[Serializable]public class Point { … }public Point[] points;public int frequency = 1;public Color centerColor;private Mesh mesh;private Vector3[] vertices;private Color[] colors;private int[] triangles;public void UpdateStar () { … }void OnEnable () { … }void OnDisable () { … }void Reset () {UpdateStar();}
}

OK我们开始写Reset。我们要做什么?我们来试试prefabs?

现在使用prefabs对于我们star并没有太多意义,因为每一个star都拥有自己的独立的Mesh。如果你想使用很多个一样的star,那在建立一个3D模型并且导入Mesh是一个好主意。这样所有的star就共享了同一个Mesh。但假设我们使用prefab,就可以实例化多个同样的star然后我们还能够调整它们。

你只要简单的拖拽一个star从层级视图到项目视图,就能建立一个prefab。对prefab的更新能够影响全部的prefab实例,因为每个prefab的修改都会触发OnDisable和OnEnable。将一个实例回复成prefab同样的状态它依然能够工作。

唯一我们没有完全做好的事情是prefab的MeshFilter会显示它的Mesh类型不匹配。这事因为prefab是一个实际的资源,而动态生成的Mesh不是。这不影响功能,但还是让我们解决它吧。

一个修改后提示类型不匹配的prefab

为了停止prefab生成它的Mesh,我们不能再调用UpdateStar方法。不幸的是,这代表我们将不能再看到预览了。我们可以用PrefabUtility.GetPrefabType方法来检测编辑窗口当前的对象是不是prefab。如果是,我们简单的不更新它就行了。

using UnityEditor;
using UnityEngine;[CustomEditor(typeof(Star))]
public class StarInspector : Editor {private static GUIContentinsertContent = new GUIContent("+", "duplicate this point"),deleteContent = new GUIContent("-", "delete this point"),pointContent = GUIContent.none,teleportContent = new GUIContent("T");private static GUILayoutOptionbuttonWidth = GUILayout.MaxWidth(20f),colorWidth = GUILayout.MaxWidth(50f);private SerializedObject star;private SerializedPropertypoints,frequency,centerColor;private int teleportingElement;void OnEnable () { … }public override void OnInspectorGUI () {star.Update();GUILayout.Label("Points");for(int i = 0; i < points.arraySize; i++){EditorGUILayout.BeginHorizontal();SerializedProperty point = points.GetArrayElementAtIndex(i);EditorGUILayout.PropertyField(point.FindPropertyRelative("offset"), pointContent);EditorGUILayout.PropertyField(point.FindPropertyRelative("color"), pointContent, colorWidth);if(GUILayout.Button(teleportContent, EditorStyles.miniButtonLeft, buttonWidth)){if(teleportingElement >= 0){points.MoveArrayElement(teleportingElement, i);teleportingElement = -1;teleportContent.tooltip = "start teleporting this point";}else{teleportingElement = i;teleportContent.tooltip = "teleport here";}}if(GUILayout.Button(insertContent, EditorStyles.miniButtonMid, buttonWidth)){points.InsertArrayElementAtIndex(i);}if(GUILayout.Button(deleteContent, EditorStyles.miniButtonRight, buttonWidth)){points.DeleteArrayElementAtIndex(i);}EditorGUILayout.EndHorizontal();}if(teleportingElement >= 0){GUILayout.Label("teleporting point " + teleportingElement);}EditorGUILayout.PropertyField(frequency);EditorGUILayout.PropertyField(centerColor);if(star.ApplyModifiedProperties() ||(Event.current.type == EventType.ValidateCommand &&Event.current.commandName == "UndoRedoPerformed")){if(PrefabUtility.GetPrefabType(target) != PrefabType.Prefab){((Star)target).UpdateStar();}}}
}
prefab没有了Mesh和预览

OK,我们完成了,真的?我没还没有对同时存在多个对象的情况进行支持。试试同时选择多个star。

还没有提供多对象编辑

让我们尝试多对象编辑功能吧。首先,我们需要给类添加一个属性让编辑器提供相应的支持。然后我们需要初始化所有target的SerializedObject,而不再只是一个。我们还需要把任何变化同步到全部的target上。

这样就能在编辑器中支持多个对象了,但如果一些star的point个数不一样,就会出错。因为在Unity的编辑器尝试读取全部点的资料的时候,有些点会不存在。我们可以在获得每个point的数据的时候检查一下这个point是否存在,如果不存在,就停止取值。所以我们只需要显示一个star所拥有的数量的point就可以了。

using UnityEditor;
using UnityEngine;[CanEditMultipleObjects, CustomEditor(typeof(Star))]
public class StarInspector : Editor {private static GUIContentinsertContent = new GUIContent("+", "duplicate this point"),deleteContent = new GUIContent("-", "delete this point"),pointContent = GUIContent.none,teleportContent = new GUIContent("T");private static GUILayoutOptionbuttonWidth = GUILayout.MaxWidth(20f),colorWidth = GUILayout.MaxWidth(50f);private SerializedObject star;private SerializedPropertypoints,frequency,centerColor;private int teleportingElement;void OnEnable () {star = new SerializedObject(targets);points = star.FindProperty("points");frequency = star.FindProperty("frequency");centerColor = star.FindProperty("centerColor");teleportingElement = -1;teleportContent.tooltip = "start teleporting this point";}public override void OnInspectorGUI () {star.Update();GUILayout.Label("Points");for(int i = 0; i < points.arraySize; i++){SerializedPropertypoint = points.GetArrayElementAtIndex(i),offset = point.FindPropertyRelative("offset");if(offset == null){break;}EditorGUILayout.BeginHorizontal();EditorGUILayout.PropertyField(offset, pointContent);EditorGUILayout.PropertyField(point.FindPropertyRelative("color"), pointContent, colorWidth);if(GUILayout.Button(teleportContent, EditorStyles.miniButtonLeft, buttonWidth)){if(teleportingElement >= 0){points.MoveArrayElement(teleportingElement, i);teleportingElement = -1;teleportContent.tooltip = "start teleporting this point";}else{teleportingElement = i;teleportContent.tooltip = "teleport here";}}if(GUILayout.Button(insertContent, EditorStyles.miniButtonMid, buttonWidth)){points.InsertArrayElementAtIndex(i);}if(GUILayout.Button(deleteContent, EditorStyles.miniButtonRight, buttonWidth)){points.DeleteArrayElementAtIndex(i);}EditorGUILayout.EndHorizontal();}if(teleportingElement >= 0){GUILayout.Label("teleporting point " + teleportingElement);}EditorGUILayout.PropertyField(frequency);EditorGUILayout.PropertyField(centerColor);if(star.ApplyModifiedProperties() ||(Event.current.type == EventType.ValidateCommand &&Event.current.commandName == "UndoRedoPerformed")){foreach(Star s in targets){if(PrefabUtility.GetPrefabType(s) != PrefabType.Prefab){s.UpdateStar();}}}}
}
scene view inspector
多对象编辑

在场景中编辑 Editing in the Scene View

现在我们拥有了一个很不错的编辑器了,但如果我们能直接在场景里编辑这些point会不会更酷一些?用OnSceneGUI事件,我们可以做到。这个方法会在一个对象被选中即将赋予target时调用。我们不能在这个事件中使用SerializedObject。事实上,你可以认为这个方法与我们编辑器类中的其它部分是完全分离的。

Why does OnSceneGUI mess with target?

Probably for backwards compatibility. Multi-object editing was introduced in Unity 3.5. Versions before that only had the target variable.

using UnityEditor;
using UnityEngine;[CanEditMultipleObjects, CustomEditor(typeof(Star))]
public class StarInspector : Editor {private static GUIContentinsertContent = new GUIContent("+", "duplicate this point"),deleteContent = new GUIContent("-", "delete this point"),pointContent = GUIContent.none,teleportContent = new GUIContent("T");private static GUILayoutOptionbuttonWidth = GUILayout.MaxWidth(20f),colorWidth = GUILayout.MaxWidth(50f);private SerializedObject star;private SerializedPropertypoints,frequency,centerColor;private int teleportingElement;void OnEnable () { … }public override void OnInspectorGUI () { … }void OnSceneGUI () {}
}

让我们设置一个方形的小手柄在star全部的point上面。我们只要在这些point的第一个重复周期里显示手柄就可以了,不需要把全部的重复周期都显示出来。放置这些手柄就好象生成Mesh一样,除了我们使用的是世界坐标系,不是本地坐标系,所以我们要用到star的transform。

我们可以通过Handles.FreeMoveHandle方法来绘制我们的手柄。首先,需要一个世界坐标系的位置,手柄的位置。其次,需要一个绘制手柄的角度,但我们不需要旋转。然后,还需要手柄的尺寸,我们用一个很小的尺寸就够了。我们用一个vector来保存这个尺寸,可以设置成(0.1, 0.1 0.1)。最后一个参数是定义手柄的形状。

How do we convert to world space?

You convert a point from local to world space by appling all transformation matrices of its object hierarchy to it. Unity takes care of this when rendering the scene, but sometimes you need to do it yourself. You can use the Transform.TransformPoint method for this.

using UnityEditor;
using UnityEngine;[CanEditMultipleObjects, CustomEditor(typeof(Star))]
public class StarInspector : Editor {private static Vector3 pointSnap = Vector3.one * 0.1f;private static GUIContentinsertContent = new GUIContent("+", "duplicate this point"),deleteContent = new GUIContent("-", "delete this point"),pointContent = GUIContent.none,teleportContent = new GUIContent("T");private static GUILayoutOptionbuttonWidth = GUILayout.MaxWidth(20f),colorWidth = GUILayout.MaxWidth(50f);private SerializedObject star;private SerializedPropertypoints,frequency,centerColor;private int teleportingElement;void OnEnable () { … }public override void OnInspectorGUI () { … }void OnSceneGUI () {Star star = (Star)target;Transform starTransform = star.transform;float angle = -360f / (star.frequency * star.points.Length);for(int i = 0; i < star.points.Length; i++){Quaternion rotation = Quaternion.Euler(0f, 0f, angle * i);Vector3 oldPoint = starTransform.TransformPoint(rotation * star.points[i].offset);Handles.FreeMoveHandle(oldPoint, Quaternion.identity, 0.04f, pointSnap, Handles.DotCap);}}
}
在场景中添加了控制手柄

现在还有什么可以做到更好吗?你可以点击一个手柄,让它变成黄色。我们需要比较一个手柄的初始化位置和返回位置。如果不同,说明用户拖动了手柄,我们需要将改变同步到star。star的Mesh使用本地坐标系,在把坐标改变保存之前,不要忘记转换坐标。

How do we convert to local space?

You have to perform the exact opposite steps for converting to world space, in reverse order. You can use the Transform.InverseTransformPoint method for this. Note that when going to world space we rotated in local space first, then transformed. So to convert back, we inverse transform first, then inverse rotate in local space.

using UnityEditor;
using UnityEngine;[CanEditMultipleObjects, CustomEditor(typeof(Star))]
public class StarInspector : Editor {private static Vector3 pointSnap = Vector3.one * 0.1f;private static GUIContentinsertContent = new GUIContent("+", "duplicate this point"),deleteContent = new GUIContent("-", "delete this point"),pointContent = GUIContent.none,teleportContent = new GUIContent("T");private static GUILayoutOptionbuttonWidth = GUILayout.MaxWidth(20f),colorWidth = GUILayout.MaxWidth(50f);private SerializedObject star;private SerializedPropertypoints,frequency,centerColor;private int teleportingElement;void OnEnable () { … }public override void OnInspectorGUI () { … }void OnSceneGUI () {Star star = (Star)target;Transform starTransform = star.transform;float angle = -360f / (star.frequency * star.points.Length);for(int i = 0; i < star.points.Length; i++){Quaternion rotation = Quaternion.Euler(0f, 0f, angle * i);Vector3oldPoint = starTransform.TransformPoint(rotation * star.points[i].offset),newPoint = Handles.FreeMoveHandle(oldPoint, Quaternion.identity, 0.04f, pointSnap, Handles.DotCap);if(oldPoint != newPoint){star.points[i].offset = Quaternion.Inverse(rotation) *starTransform.InverseTransformPoint(newPoint);star.UpdateStar();}}}
}
我们可以在场景中编辑了

有用了!不过我们还没支持Undo!这里我们不能靠SerializedObject来解决问题,不过幸好这些手柄可以支持Undo。我们只需要告诉编辑器哪个对象被改变了,我们还应该为这次改变起一个名字。我们可以用Undo.SetSnapshotTarget来做这些事。

What’s a snapshot?

If an undo step would be created for each GUI event, dragging a handle would result in an undo history filled with dozens of tiny modifications. Instead, the handles make a copy – a snapshot – of the object when movement begins and only register a single undo step with the copy when movement ends. SetSnapshotTarget tells the handles which object to use for this.
All Unity editor GUI elements essentialy do the same thing, whether it’s for draggin handles, sliding numbers, typing text, or whatever.

using UnityEditor;
using UnityEngine;[CanEditMultipleObjects, CustomEditor(typeof(Star))]
public class StarInspector : Editor {private static Vector3 pointSnap = Vector3.one * 0.1f;private static GUIContentinsertContent = new GUIContent("+", "duplicate this point"),deleteContent = new GUIContent("-", "delete this point"),pointContent = GUIContent.none,teleportContent = new GUIContent("T");private static GUILayoutOptionbuttonWidth = GUILayout.MaxWidth(20f),colorWidth = GUILayout.MaxWidth(50f);private SerializedObject star;private SerializedPropertypoints,frequency,centerColor;private int teleportingElement;void OnEnable () { … }public override void OnInspectorGUI () { … }void OnSceneGUI () {Star star = (Star)target;Transform starTransform = star.transform;//Undo.SetSnapshotTarget(star, "Move Star Point");Undo.RecordObject(star, "Move star transform");float angle = -360f / (star.frequency * star.points.Length);for(int i = 0; i < star.points.Length; i++){Quaternion rotation = Quaternion.Euler(0f, 0f, angle * i);Vector3oldPoint = starTransform.TransformPoint(rotation * star.points[i].offset),newPoint = Handles.FreeMoveHandle(oldPoint, Quaternion.identity, 0.04f, pointSnap, Handles.DotCap);if(oldPoint != newPoint){star.points[i].offset = Quaternion.Inverse(rotation) *starTransform.InverseTransformPoint(newPoint);star.UpdateStar();}}}
}


<>使用Ctrl + z就可以使用了

这样,我们终于完成了!一个有趣的设计过程,不是吗?下面是工程下载地址!


star.txt (下载32 )

转自:http://www.unity.5helpyou.com/3131.html


这篇关于Unity教程之-制作闪亮的星星Star(四):Unity Editor编辑器实现Undo的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/282422

相关文章

C++对象布局及多态实现探索之内存布局(整理的很多链接)

本文通过观察对象的内存布局,跟踪函数调用的汇编代码。分析了C++对象内存的布局情况,虚函数的执行方式,以及虚继承,等等 文章链接:http://dev.yesky.com/254/2191254.shtml      论C/C++函数间动态内存的传递 (2005-07-30)   当你涉及到C/C++的核心编程的时候,你会无止境地与内存管理打交道。 文章链接:http://dev.yesky

ONLYOFFICE 8.1 版本桌面编辑器测评

在现代办公环境中,办公软件的重要性不言而喻。从文档处理到电子表格分析,再到演示文稿制作,强大且高效的办公软件工具能够极大提升工作效率。ONLYOFFICE 作为一个功能全面且开源的办公软件套件,一直以来都受到广大用户的关注与喜爱。而其最新发布的 ONLYOFFICE 8.1 版本桌面编辑器,更是带来了诸多改进和新特性。本文将详细评测 ONLYOFFICE 8.1 版本桌面编辑器,探讨其在功能、用户

通过SSH隧道实现通过远程服务器上外网

搭建隧道 autossh -M 0 -f -D 1080 -C -N user1@remotehost##验证隧道是否生效,查看1080端口是否启动netstat -tuln | grep 1080## 测试ssh 隧道是否生效curl -x socks5h://127.0.0.1:1080 -I http://www.github.com 将autossh 设置为服务,隧道开机启动

时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测

时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测 目录 时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测基本介绍程序设计参考资料 基本介绍 MATLAB实现LSTM时间序列未来多步预测-递归预测。LSTM是一种含有LSTM区块(blocks)或其他的一种类神经网络,文献或其他资料中LSTM区块可能被描述成智能网络单元,因为

vue项目集成CanvasEditor实现Word在线编辑器

CanvasEditor实现Word在线编辑器 官网文档:https://hufe.club/canvas-editor-docs/guide/schema.html 源码地址:https://github.com/Hufe921/canvas-editor 前提声明: 由于CanvasEditor目前不支持vue、react 等框架开箱即用版,所以需要我们去Git下载源码,拿到其中两个主

android一键分享功能部分实现

为什么叫做部分实现呢,其实是我只实现一部分的分享。如新浪微博,那还有没去实现的是微信分享。还有一部分奇怪的问题:我QQ分享跟QQ空间的分享功能,我都没配置key那些都是原本集成就有的key也可以实现分享,谁清楚的麻烦详解下。 实现分享功能我们可以去www.mob.com这个网站集成。免费的,而且还有短信验证功能。等这分享研究完后就研究下短信验证功能。 开始实现步骤(新浪分享,以下是本人自己实现

基于Springboot + vue 的抗疫物质管理系统的设计与实现

目录 📚 前言 📑摘要 📑系统流程 📚 系统架构设计 📚 数据库设计 📚 系统功能的具体实现    💬 系统登录注册 系统登录 登录界面   用户添加  💬 抗疫列表展示模块     区域信息管理 添加物资详情 抗疫物资列表展示 抗疫物资申请 抗疫物资审核 ✒️ 源码实现 💖 源码获取 😁 联系方式 📚 前言 📑博客主页:

探索蓝牙协议的奥秘:用ESP32实现高质量蓝牙音频传输

蓝牙(Bluetooth)是一种短距离无线通信技术,广泛应用于各种电子设备之间的数据传输。自1994年由爱立信公司首次提出以来,蓝牙技术已经经历了多个版本的更新和改进。本文将详细介绍蓝牙协议,并通过一个具体的项目——使用ESP32实现蓝牙音频传输,来展示蓝牙协议的实际应用及其优点。 蓝牙协议概述 蓝牙协议栈 蓝牙协议栈是蓝牙技术的核心,定义了蓝牙设备之间如何进行通信。蓝牙协议

Steam邮件推送内容有哪些?配置教程详解!

Steam邮件推送功能是否安全?如何个性化邮件推送内容? Steam作为全球最大的数字游戏分发平台之一,不仅提供了海量的游戏资源,还通过邮件推送为用户提供最新的游戏信息、促销活动和个性化推荐。AokSend将详细介绍Steam邮件推送的主要内容。 Steam邮件推送:促销优惠 每当平台举办大型促销活动,如夏季促销、冬季促销、黑色星期五等,用户都会收到邮件通知。这些邮件详细列出了打折游戏、

python实现最简单循环神经网络(RNNs)

Recurrent Neural Networks(RNNs) 的模型: 上图中红色部分是输入向量。文本、单词、数据都是输入,在网络里都以向量的形式进行表示。 绿色部分是隐藏向量。是加工处理过程。 蓝色部分是输出向量。 python代码表示如下: rnn = RNN()y = rnn.step(x) # x为输入向量,y为输出向量 RNNs神经网络由神经元组成, python