http://www.xuanyusong.com/archives/2303

Scene视图是编辑游戏模型的地方,其实它还可以进行编辑。如下图所示,我给Scene视图做了简单的编辑。

【unity】拓展Scene视图(三)_editor

 

Scene视图的拓展是基于对象的,意思就是你必须在Hierarchy视图中选择一个对象才行。Hierarchy视图中选择不同的对象可以有不同的Scene视图。图中我们创建了一个立方体对象,接着给它绑定一个脚本。

【unity】拓展Scene视图(三)_editor_02

 

Test.cs 是个空空的脚本。

 

C#

1

2

3

4

5

6

7

using UnityEngine;

using System.Collections;

 

public class Test : MonoBehaviour

{

 

}

然后在Project视图中创建一个Editor文件夹,把MyEditor.cs放进去。 

 

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

using UnityEditor;

using UnityEngine;

 

//自定义Tset脚本

[CustomEditor(typeof(Test))]

//请继承Editor

public class MyEditor : Editor

{

 

void OnSceneGUI()

{

//得到test脚本的对象

Test test = (Test) target;

 

//绘制文本框

Handles.Label(test.transform.position + Vector3.up*2,

                    test.transform.name +" : "+ test.transform.position.ToString() );

 

//开始绘制GUI

Handles.BeginGUI();

 

    //规定GUI显示区域

    GUILayout.BeginArea(new Rect(100, 100, 100, 100));

 

    //GUI绘制一个按钮

    if(GUILayout.Button("这是一个按钮!"))

{

Debug.Log("test");

}

//GUI绘制文本框

GUILayout.Label("我在编辑Scene视图");

 

    GUILayout.EndArea();

 

Handles.EndGUI();

}

 

}

 此时,你可以把之前的Test.cs脚本绑定在任意对象身上,然后在Hierarchy视图中点击对象即可在Scene视图中看到编辑的视图啦。

 

【unity】拓展Scene视图(三)_editor_03

 

 

最后我在说一下,在OnSceneGUI()中只能通过Handles来绘制新视图,如果你想引入GUI的元素哪么就需要使用BeginGUI()和EndGUI()组合的使用。 Handles还提供了很多编辑视图的方式,详细信息大家请看API http://docs.unity3d.com/Documentation/ScriptReference/Handles.ArrowCap.html  这里我就不在赘述。 

 

本文下载地址:http://vdisk.weibo.com/s/AB2i-

 今天我同事问我,上面的方法,必须鼠标选中才可以显示,能不能不选中也能显示?

http://answers.unity3d.com/questions/44771/labeling-objects-in-the-scene-editor-view.html

把下面的代码放在Editor目录下即可。

 

C#

1

2

3

4

5

6

7

8

9

10

11

12

using UnityEngine;

using System.Collections;

using UnityEditor;

 

public class NewBehaviourScript : Editor {

 

[DrawGizmo(GizmoType.SelectedOrChild | GizmoType.NotSelected)]

static void DrawGameObjectName(Transform transform, GizmoType gizmoType)

{  

Handles.Label(transform.position, transform.gameObject.name);

}

}