今天这篇文章主要说的就是Unity3d自定义一个编辑器组件/插件的简易教程,希望对同学们有帮助。
这个教程将让你学会如何创建一个星型控件以及如何制作这个控件的自定义编辑器。你将学会:
动态的建立Mesh。
使用一个嵌套类。
建立一个自定义编辑器。
使用SerializedObject。
支持所见即所得。
对Undo、Redo、Reset和prefab提供支持。
支持多对象编辑。
支持场景视图内编辑。
我们假设你已经学会了Unity C#的基础编程知识,以及Unity 编辑器的基础知识。如果你已经完成了相关的学习,Let's Go!
建立Star类 Creating the star
我们建立一个全新的Unity工程,然后建立一个新的C#脚本,将它命名为Star。我们将用这个脚本,建立一个由三角面拼接成的星,这里需要一个Mesh。
什么是Mesh?
3D模型是由多边形拼接而成,一个复杂的多边形,实际上是由多个三角面拼接而成。所以一个3D模型的表面是由多个彼此相连的三角面构成。三维空间中,构成这些三角面的点以及三角形的边的集合就是Mesh。
using UnityEngine;
public class Star : MonoBehaviour {
private Mesh mesh;
}
任何对于Mesh的使用,都必须搭配一个MeshFilter组件,而MeshFilter又被用于MeshRenderer组件。只有这样,才能被Unity绘制。所以,这些组件都必须被加载到GameObject对象上,我们的Star对象也必须这么做。
当然,我们可以手动添加这些组件,但默认的自动添加是一个更好的办法。所以我们需要添加一个RequireComponent类作为Star对象的一个特性。
什么是类的特性?
特性像对类附加一个标签,用来告诉编译器这个类需要如何处理。是除了类声明的代码之外,对类做的附加说明。另外,特性不止针对类,对方法和属性同样适用。
typeof有什么用?
typeof是一种运算符,能够获得任何类的类型描述数据,数据里最常用的就是类的名字。那为什么不直接在代码里写类的名字就好呢?因为代码中所有的赋值和运算都需要变量,直接使用类的名字会导致编译错误。
using UnityEngine;
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Star : MonoBehaviour {
private Mesh mesh;
}
现在,我们建立一个新的空GameObject,将它命名为My First Star,然后拖拽我们的脚本Star到My First Star上。你可以看到,My First Star拥有了两个组件,MeshRenderer和Star。
拖动一个,得到三个
下一个步骤是建立一个Mesh。我们需要在Unity的Start事件里来做这些事,Start事件将在程序启动的时候发生。我们还需要在MeshFilter中给这个新的Mesh起一个名字。
using UnityEngine;
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Star : MonoBehaviour {
private Mesh mesh;
void Start () {
GetComponent<MeshFilter>().mesh = mesh = new Mesh();
mesh.name = "Star Mesh";
}
}
无编辑器模式与实时预览模式
当然,现在我们在预览模式下还看不到任何东西,因为Mesh还是空的。所以让我们开始编辑顶点数组吧,我们的Star类需要一个用来设置顶点数量的属性,以及这些定点与中心的相对距离。
第一个顶点是Star的中心点,其余的顶点将顺时针排列。我们将使用四元数来计算这些点的排列。因为我们假设俯视Z轴,所以,轮转的角度是负数,否则,将使这些点做逆时针排列。我们不需要设置第一个点,因为vector默认会被设置成0, Mesh中使用本地坐标系。
using UnityEngine;
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Star : MonoBehaviour {
public Vector3 point = Vector3.up;
public int numberOfPoints = 10;
private Mesh mesh;
private Vector3[] vertices;
void Start () {
GetComponent<MeshFilter>().mesh = mesh = new Mesh();
mesh.name = "Star Mesh";
vertices = new Vector3[numberOfPoints + 1];
float angle = -360f / numberOfPoints;
for(int v = 1; v < vertices.Length; v++){
vertices[v] = Quaternion.Euler(0f, 0f, angle * (v - 1)) * point;
}
mesh.vertices = vertices;
}
}
新的编辑器属性
三角面会被保存成顶点数组,每个面三个顶点。因为我们使用三角形来描述多边形,每个三角形都起始于相同的中点,并且与其他的三角形相连。最后一个三角形与第一个三角形相连。例如,如果有四个三角形,那么顶点数组如下{0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 1}。
using UnityEngine;
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Star : MonoBehaviour {
public Vector3 point = Vector3.up;
public int numberOfPoints = 10;
private Mesh mesh;
private Vector3[] vertices;
private int[] triangles;
void Start () {
GetComponent<MeshFilter>().mesh = mesh = new Mesh();
mesh.name = "Star Mesh";
vertices = new Vector3[numberOfPoints + 1];
triangles = new int[numberOfPoints * 3];
float angle = -360f / numberOfPoints;
for(int v = 1, t = 1; v < vertices.Length; v++, t += 3){
vertices[v] = Quaternion.Euler(0f, 0f, angle * (v - 1)) * point;
triangles[t] = v;
triangles[t + 1] = v + 1;
}
triangles[triangles.Length - 1] = 1;
mesh.vertices = vertices;
mesh.triangles = triangles;
}
}
一个简单的星星
现在,我们的星星看起来还只是一个简单的多边形。Unity也提示说丢失材质坐标,因为默认的Shader需要这些坐标。我们不会使用一个纹理来描绘所有的星星,让我们通过建立我们自己的Shader来消除这个警告,这个Shader将只使用顶点着色。
我们建立一个新的Shader将它命名为Star,然后写入以下代码。
什么是CGPROGRAM?
Basically, data flows from the Unity engine into the graphics card, where it's processed per vertex. Then interpolated data flows from the vertices down to the individual pixels. In this case, we pass position and color data all the way down. The only additional thing we do is convert vertex positions from world space to screen space.
The statements above the CGPROGRAM switch off default lighting and depth buffer writing. Culling is switched off so we can see the triangles from both sides, not just the front. "Blend SrcAlpha OneMinusSrcAlpha" is default alpha blending, allowing for transparency.
为什么不使用fixed-function shader?
fixed-function shader已经属于过时的技术了。 CGPROGRAM 在将数据转化成屏幕像素方面拥有更强大的功能。
Shader "Star"{
SubShader{
Tags{ "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
Blend SrcAlpha OneMinusSrcAlpha
Cull Off
Lighting Off
ZWrite Off
Pass{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
struct data {
float4 vertex : POSITION;
fixed4 color: COLOR;
};
data vert (data v) {
v.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
return v;
}
fixed4 frag(data f) : COLOR {
return f.color;
}
ENDCG
}
}
}
现在我们建立一个新的材质球,命名为Star,将Shader设置为我们刚刚编写的Star,并且将这个材质球赋予My First Star。
添加材质球之后
顶点着色默认是白色,所以我们的多边形现在变成了白色。我们想要一个更漂亮的星星。所以我们来为每个点定义一种颜色。
我们再添加一个frequency属性,这样我们就能让程序自动重复点的序列,而不用我们逐个定义全部的点。这个选项取代了numberOfPoints。
我们在最后需要确认frequency属性是否正确,并且星星至少拥有一个点。如果没有,我们的代码就可能出错。
Why check both for null and the length?
When freshly created, our star component won't have an array yet. It's also technically possible for scripts to explicitly set our array to null later on. We need to watch out for that, to prevent errors. Only if the array does exists do we go ahead and check its length as well.
using UnityEngine;
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Star : MonoBehaviour {
public Vector3[] points;
public int frequency = 1;
private Mesh mesh;
private Vector3[] vertices;
private int[] triangles;
void Start () {
GetComponent<MeshFilter>().mesh = mesh = new Mesh();
mesh.name = "Star Mesh";
if(frequency < 1){
frequency = 1;
}
if(points == null || points.Length == 0){
points = new Vector3[]{ Vector3.up};
}
int numberOfPoints = frequency * points.Length;
vertices = new Vector3[numberOfPoints + 1];
triangles = new int[numberOfPoints * 3];
float angle = -360f / numberOfPoints;
for(int iF = 0, v = 1, t = 1; iF < frequency; iF++){
for(int iP = 0; iP < points.Length; iP += 1, v += 1, t += 3){
vertices[v] = Quaternion.Euler(0f, 0f, angle * (v - 1)) * points[iP];
triangles[t] = v;
triangles[t + 1] = v + 1;
}
}
triangles[triangles.Length - 1] = 1;
mesh.vertices = vertices;
mesh.triangles = triangles;
}
}
配置好的点
我们需要些颜色!如果把全部的顶点都指定相同的颜色就很简单,但这样太无聊了。我们来试试给每个顶点分配一个颜色。我们需要一个数组来保存这些颜色数据,而且必须保持颜色和顶点的数量一致。这有点小麻烦,我们干脆换成另外一种方式,在Star类中建立一个新的类,这个类可以保存一个顶点的颜色和位置。然后我们可以用这个类的数组来代替vector数组。
这类叫Point,如果在Star类之外使用,就是Star.Point。在Star里面Point就可以了。为了让Unity能够将Point序列化,我们为Point添加System.Serializable特性。
为什么不用结构体?
Because Star.Point is so lightweight and its data is always needed all at once, it would make sense to use a struct type and avoid the overhead that objects add. However, Unity does not support serialization of custom struct types. So you're stuck using classes to bundle data you want to store.
If you're really concerned about the object overhead and possible null errors, you can always store the offset and color data in two separate arrays. However, then you would need to make sure that these arrays always stay synchronized. While that is definitely doable, the class approach is simpler. That's why I use it in this tutorial.
using System;
using UnityEngine;
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Star : MonoBehaviour {
[Serializable]
public class Point {
public Color color;
public Vector3 offset;
}
public Point[] points;
public int frequency = 1;
private Mesh mesh;
private Vector3[] vertices;
private Color[] colors;
private int[] triangles;
void Start () {
GetComponent<MeshFilter>().mesh = mesh = new Mesh();
mesh.name = "Star Mesh";
if(frequency < 1){
frequency = 1;
}
if(points == null || points.Length == 0){
points = new Point[]{ new Point()};
}
int numberOfPoints = frequency * points.Length;
vertices = new Vector3[numberOfPoints + 1];
colors = new Color[numberOfPoints + 1];
triangles = new int[numberOfPoints * 3];
float angle = -360f / numberOfPoints;
for(int iF = 0, v = 1, t = 1; iF < frequency; iF++){
for(int iP = 0; iP < points.Length; iP += 1, v += 1, t += 3){
vertices[v] = Quaternion.Euler(0f, 0f, angle * (v - 1)) * points[iP].offset;
colors[v] = points[iP].color;
triangles[t] = v;
triangles[t + 1] = v + 1;
}
}
triangles[triangles.Length - 1] = 1;
mesh.vertices = vertices;
mesh.colors = colors;
mesh.triangles = triangles;
}
}
有了颜色之后
最后是关于中心点的。现在,我们还没有给它设置颜色,所以它一直保持着透明。让我们来为它添加一个颜色属性,最终,这个星星看上去变漂亮了。
using System;
using UnityEngine;
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Star : MonoBehaviour {
[Serializable]
public class Point {
public Color color;
public Vector3 offset;
}
public Point[] points;
public int frequency = 1;
public Color centerColor;
private Mesh mesh;
private Vector3[] vertices;
private Color[] colors;
private int[] triangles;
void Start () {
GetComponent<MeshFilter>().mesh = mesh = new Mesh();
mesh.name = "Star Mesh";
if(frequency < 1){
frequency = 1;
}
if(points == null || points.Length == 0){
points = new Point[]{ new Point()};
}
int numberOfPoints = frequency * points.Length;
vertices = new Vector3[numberOfPoints + 1];
colors = new Color[numberOfPoints + 1];
triangles = new int[numberOfPoints * 3];
float angle = -360f / numberOfPoints;
colors[0] = centerColor;
for(int iF = 0, v = 1, t = 1; iF < frequency; iF++){
for(int iP = 0; iP < points.Length; iP += 1, v += 1, t += 3){
vertices[v] = Quaternion.Euler(0f, 0f, angle * (v - 1)) * points[iP].offset;
colors[v] = points[iP].color;
triangles[t] = v;
triangles[t + 1] = v + 1;
}
}
triangles[triangles.Length - 1] = 1;
mesh.vertices = vertices;
mesh.colors = colors;
mesh.triangles = triangles;
}
}
漂亮的星星,麻烦的编辑器
建立编辑器 Creating the Inspector
现在Star看起来不错,但设计起来有些麻烦。默认的编辑器有点蛋疼,让我们自己做一个!
所有编辑器类的代码,都需要放在Editor文件夹下,只有这样Unity才能正确的识别这代码。Editor的名字对就行,放在哪倒无所谓。我们现在把Editor建立在根目录也就是Assets下。然后再建一个StarInspector类的代码文件,放在Editor里面。
编辑器的类型?
需要了解的是,编辑器面板不只有一个类型。我们这个例子里面使用的是属性面板——Inspector,其余还有 EditorWindow——编辑对话框,可以实现一个完全自定义的弹出式对话框,还有ScriptableWizard——向导对话框,以及编辑器菜单。
目录结构
因为我们的类是一个编辑器类,它需要继承Editor类而不是MonoBehaviour。我们还需要添加一个属性来告诉Unity,这个类是为Star类定义编辑器的。
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Star))]
public class StarInspector : Editor {}
到目前为止,我们没有改变Star的编辑器。我们需要替换默认的编辑器。我们可以通过重载Editor 类的OnInspectorGUI事件来实现。
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Star))]
public class StarInspector : Editor {
public override void OnInspectorGUI () {}
}
一个空的编辑器
默认的编辑器捏?没了?
因为我们没有在OnInspectorGUI事件里写任何代码,所以一切都是空白的。DrawDefaultInspector方法可以用来绘制默认的编辑器界面,但我们本来就不想要这个,还是试试别的吧。
我们首先要确认是哪个Star对象被选中,应该在编辑器中被显示。我们可以使用target属性来表示这个对象,target属性是Editor的一个属性,我们继承了Editor,所以也继承了这个属性,可以直接使用它,非常方便。虽然这不是必须的,我们可以用 SerializedObject来包装target,这么做会很方便,因为会使对很多编辑器的操作支持变得简单,比如undo。
我们使用了SerializedObject,可以通过SerializedProperty对象来提取它的数据。我们要在OnEnable事件里初始化所有的star类的变量。这个事件会在一个添加Star组件的GameObject被选中时发生。
What's a SerializedObject?
SerializedObject is a class that acts as a wrapper or proxy for Unity objects. You can use it to extract data from the object even if you don't have a clue what's inside it. This is how the Unity inspector can show default inspectors for anything you create yourself. As a bonus, you get undo support for free.
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Star))]
public class StarInspector : Editor {
private SerializedObject star;
private SerializedProperty
points,
frequency,
centerColor;
void OnEnable () {
star = new SerializedObject(target);
points = star.FindProperty("points");
frequency = star.FindProperty("frequency");
centerColor = star.FindProperty("centerColor");
}
public override void OnInspectorGUI () {}
}
每一次编辑器更新的时候,我们都需要确定SerializedObject被实时更新了。这就是我们要在OnInspectorGUI事件里做的第一件事。之后我们可以简单的调用EditorGUILayout.PropertyField来显示我们的属性,显示points及其内部的所有元素。之后我们结束所有属性修改并应用到选定的组件。
What's EditorGUILayout?
EditorGUILayout is a utility class for displaying stuff in the Unity editor. It contains methods for drawing all kinds of things, in this case we're simply using the default method for drawing a SerializedProperty.
There's also an EditorGUI utility class which does that same thing, but requires you to perform your own GUI layout.
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Star))]
public class StarInspector : Editor {
private SerializedObject star;
private SerializedProperty
points,
frequency,
centerColor;
void OnEnable () { … }
public override void OnInspectorGUI () {
star.Update();
EditorGUILayout.PropertyField(points, true);
EditorGUILayout.PropertyField(frequency);
EditorGUILayout.PropertyField(centerColor);
star.ApplyModifiedProperties();
}
}
一个被重建的编辑器
现在的编辑器和默认的差不多,我们可以做的更好。我们需要重新整理一下points的显示格式,让每个点的颜色和位移信息合并为一组显示。
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Star))]
public class StarInspector : Editor {
private SerializedObject star;
private SerializedProperty
points,
frequency,
centerColor;
void OnEnable () { … }
public override void OnInspectorGUI () {
star.Update();
for(int i = 0; i < points.arraySize; i++){
EditorGUILayout.BeginHorizontal();
SerializedProperty point = points.GetArrayElementAtIndex(i);
EditorGUILayout.PropertyField(point.FindPropertyRelative("offset"));
EditorGUILayout.PropertyField(point.FindPropertyRelative("color"));
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.PropertyField(frequency);
EditorGUILayout.PropertyField(centerColor);
star.ApplyModifiedProperties();
}
}
排版不良的编辑器
我们需要修正这个排版。让我们去掉颜色和位置的标签,设置颜色条的最大长度为50像素。我们通过EditorGUILayout.PropertyField方法的额外参数能够实现。因为我们对所有的对象都使用相同的配置,所以我们使用静态变量来保存这些设置。
然后再通过GUILayout.Label方法来给所有的points添加一个统一的标签。
What's a GUIContent?
GUIContent is a wrapper object for text, textures, and tooltips that you typically use as labels.
Why use GUILayout instead of EditorGUILayout?
You use the same Unity GUI system for editors that you can use for your games. GUILayout provided basic functionality like labels and buttons, while EditorGUILayout provides extra editor-specific stuff like input fields.
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Star))]
public class StarInspector : Editor {
private static GUIContent pointContent = GUIContent.none;
private static GUILayoutOption colorWidth = GUILayout.MaxWidth(50f);
private SerializedObject star;
private SerializedProperty
points,
frequency,
centerColor;
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);
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.PropertyField(frequency);
EditorGUILayout.PropertyField(centerColor);
star.ApplyModifiedProperties();
}
}
一个紧凑的编辑器
最终,看上去好多了!现在,如果我们能方便的添加和删除points就更好了。让我们试试添加这些按钮吧。
我们为每个point添加两个按钮,一个是“+”用来插入point,一个是"-"用来删除point。我们再添加一些说明使用户能够了解这些按钮的用途。我们还需要控制按钮宽度,将样式设置成mini buttons,因为这些按钮要小一些。
How does GUILayout.Button work?
The method GUILayout.Button both shows a button and returns whether it was clicked. So you typically call it inside an if statement and perform the necessary work in the corresponding code block.
What actually happens is that your own GUI method, in this case OnInspectorGUI, gets called far more often than just once. It gets called when performing layout, when repainting, and whenever a significant GUI event happens, which is quite often. Only when a mouse click event comes along that is consumed by the button, will it return true.
To get an idea, put Debug.Log(Event.current); at the start of your OnInspectorGUI method and fool around a bit.
Usually you need not worry about this, but be aware of it when performing heavy work like generating textures. You don't want to do that dozens of times per second if you don't need to.
What are the contents of a new item?
If you insert a new array element via a SerializedProperty, the new element will be a duplicate of the element just above it. If there's no other element, it gets default values.
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Star))]
public class StarInspector : Editor {
private static GUIContent
insertContent = new GUIContent("+", "duplicate this point"),
deleteContent = new GUIContent("-", "delete this point"),
pointContent = GUIContent.none;
private static GUILayoutOption
buttonWidth = GUILayout.MaxWidth(20f),
colorWidth = GUILayout.MaxWidth(50f);
private SerializedObject star;
private SerializedProperty
points,
frequency,
centerColor;
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(insertContent, EditorStyles.miniButtonLeft, buttonWidth)){
points.InsertArrayElementAtIndex(i);
}
if(GUILayout.Button(deleteContent, EditorStyles.miniButtonRight, buttonWidth)){
points.DeleteArrayElementAtIndex(i);
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.PropertyField(frequency);
EditorGUILayout.PropertyField(centerColor);
star.ApplyModifiedProperties();
}
}
添加了传送按钮和提示
看上去不错,但是怎么移动points?如果我们能够直接拖动这些点来排列它们,那就太棒了。虽然这肯定是整齐的,让我们用一个简单办法来解决它。
我们可以给每个point添加一个传送按钮。点一下,你就激活了这个point的显示。点另一个,就会跳转到另一个point,同时移动视角到当前point。
这种方式需要我们来记录哪个point是当前的焦点。我们可以使用point的索引值来记录焦点,用-1表示焦点为空。我们将改变按钮的提示信息,信息将根据按钮的状态而定,并添加一个标签来告诉用户该做什么。
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Star))]
public class StarInspector : Editor {
private static GUIContent
insertContent = new GUIContent("+", "duplicate this point"),
deleteContent = new GUIContent("-", "delete this point"),
pointContent = GUIContent.none,
teleportContent = new GUIContent("T");
private static GUILayoutOption
buttonWidth = GUILayout.MaxWidth(20f),
colorWidth = GUILayout.MaxWidth(50f);
private SerializedObject star;
private SerializedProperty
points,
frequency,
centerColor;
private int teleportingElement;
void OnEnable () {
star = new SerializedObject(target);
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++){
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);
star.ApplyModifiedProperties();
}
}
有传送按钮的编辑器
所见即所得 WYSIWYG
我们的编辑器对point已经很友好了,但我们还不能实时看到我们编辑过程中的结果。是时候改变这一切了!
第一件事是让Unity了解,我们的组件需要在编辑模式下被激活。我们通过ExecuteInEditMode类来声明这一属性。此后,star在编辑中的任何显示,都会调用Start方法。
因为我们建立了一个Mesh在Start方法中,它将在编辑模式下被创建。正如我们把Mesh存放在MeshFilter中,它将被保存于场景中。我们不希望这样,因为我们需要动态的创建Mesh。我们可以设置HideFlags来阻止Unity保存Mesh。于是,我们还需要确认Mesh被清理时,编辑器已经不再需要它。OnDisable事件会在每一个组件实效时被调用,它可以帮我们处理这些事情。我们需要在OnDisable中清理MeshFilter来阻止它发出缺少Mesh的警告。
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;
void Start () {
GetComponent<MeshFilter>().mesh = mesh = new Mesh();
mesh.name = "Star Mesh";
mesh.hideFlags = HideFlags.HideAndDontSave;
if(frequency < 1){
frequency = 1;
}
if(points == null || points.Length == 0){
points = new Point[]{ new Point()};
}
int numberOfPoints = frequency * points.Length;
vertices = new Vector3[numberOfPoints + 1];
colors = new Color[numberOfPoints + 1];
triangles = new int[numberOfPoints * 3];
float angle = -360f / numberOfPoints;
colors[0] = centerColor;
for(int iF = 0, v = 1, t = 1; iF < frequency; iF++){
for(int iP = 0; iP < points.Length; iP += 1, v += 1, t += 3){
vertices[v] = Quaternion.Euler(0f, 0f, angle * (v - 1)) * points[iP].offset;
colors[v] = points[iP].color;
triangles[t] = v;
triangles[t + 1] = v + 1;
}
}
triangles[triangles.Length - 1] = 1;
mesh.vertices = vertices;
mesh.colors = colors;
mesh.triangles = triangles;
}
void OnDisable () {
if(Application.isEditor){
GetComponent<MeshFilter>().mesh = null;
DestroyImmediate(mesh);
}
}
}
编辑模式下的星星
我们的星星已经显示在了编辑模式中!当我们在一个对象上关闭Star组件,星星的Mesh将被消除。当我们启用Star组件,它将不再恢复。因为Start方法仅在组件第一次激活时被调用。解决的办法是将我们的初始化代码移动到OnEnable事件中去。
做好之后,我们进一步重构代码,让我们能随时初始化Mesh。为了在不需要的时候不进行初始化,我们还需要添加少量的检查。
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 () {
if(mesh == null){
GetComponent<MeshFilter>().