unity中自定义窗口的扩展

1,新建C#脚本命名为MyWindowEditor

脚本内容如下:

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class MyWindowEditor : EditorWindow {

	[MenuItem("GameObject/ShowWindow")]
    static void ShowWindow()
    {
        Rect theRect = new Rect(0, 0, 500, 500);
        MyWindowEditor window=(MyWindowEditor)EditorWindow.GetWindowWithRect(typeof(MyWindowEditor),theRect,true,"我的窗口");
        //若为false,则可以进行拖动,true为独立的窗口,窗口类型true表示窗口不会被别的窗口覆盖
        window.Show();
    }
}

结果如下:

unity中自定义窗口的扩展_第1张图片

2.在窗口中进行一些基础设置

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class MyWindowEditor : EditorWindow {
    bool groundEnable = false;//一个布尔值的变量
    float value1 = 0;
    float value2 = 0;
    [MenuItem("GameObject/ShowWindow")]
    static void ShowWindow()
    {
        Rect theRect = new Rect(0, 0, 500, 500);
        MyWindowEditor window=(MyWindowEditor)EditorWindow.GetWindowWithRect(typeof(MyWindowEditor),theRect,true,"我的窗口");
        //若为false,则可以进行拖动,true为独立的窗口,窗口类型true表示窗口不会被别的窗口覆盖
        window.Show();
    }
    void OnGUI()
    {
        if(GUILayout.Button("打开通知",GUILayout.Width(220)))
        {
            this.ShowNotification(new GUIContent("要通知的内容"));
        }
        if (GUILayout.Button("关闭通知", GUILayout.Width(220)))
        {
            this.RemoveNotification();
        }
        if (GUILayout.Button("关闭窗口", GUILayout.Width(220)))
        {
            this.Close();
        }
        GUILayout.Label("以下是基础设置");
        groundEnable = EditorGUILayout.BeginToggleGroup("启用", groundEnable);
        value1 = EditorGUILayout.FloatField("值1", value1);
        value2 = EditorGUILayout.FloatField("值2", value2);
        //用复写框把选项管理起来
        EditorGUILayout.EndFadeGroup();
    }
}

窗口结果如下:

unity中自定义窗口的扩展_第2张图片

以下是窗口中常用到的函数:

//窗口获得焦点的时候被调用
    void OnFocus()
    {
        Debug.Log("窗口获得了焦点");
    }
    //窗口失去焦点的时候被调用
    void OnLostFocus()
    {
        Debug.Log("窗口失去了焦点");
    }
    void OnHierarchyChange()
    {
        Debug.Log("层次面板的对象发生改变");
    }
    void OnProjectChange()
    {
        Debug.Log("项目面板的对象发生改变");
    }
    void OnSelectionChange()
    {
        foreach(Transform item in Selection.transforms)
        {
            Debug.Log("被选中的物体是" + item.name);
        }
    }
    void OnDestroy()
    {
        Debug.Log("窗口被关闭了");
    }

unity中自定义窗口的扩展_第3张图片

你可能感兴趣的:(Unity)