使用自定义Inspector扩展Unity UI组件

Ekn*_*oes 6 c# unity-game-engine unity3d-gui

是否可以扩展新的单位ui组件,例如变换组件?因为当我尝试扩展按钮而不是转换组件时没有任何反应

using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Transform))]
public class CustomTransform : Editor
{
    public override void OnInspectorGUI()
    {            
    }
}
Run Code Online (Sandbox Code Playgroud)

Gre*_*sek 15

是的,您可以扩展UI组件并将它们编写为自己的自定义检查器.您只需要记住使用正确的命名空间,并且还要从正确的Inspector类继承.

你当然也可以覆盖!

这里的示例是UISegmentedControlButton

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;

public class UISegmentedControlButton : Button {

public Sprite offSprite;
public Sprite onSprite;
public Color offTextColor = Color.white;
public Color onTextColor = Color.white;

private bool isSelected;
public bool IsSelected {
    get {
        return isSelected;
    }
    set {
        isSelected = value;

        Text text = this.transform.GetComponentInChildren<Text>();

        if (value) {
            this.GetComponent<Image>().sprite = onSprite;
            text.color = onTextColor;
        } else {
            this.GetComponent<Image>().sprite = offSprite;
            text.color = offTextColor;
        }
    }
}




public override void OnPointerClick(PointerEventData eventData) {

    this.transform.parent.GetComponent<UISegmentedControl>().SelectSegment(this);
    base.OnPointerClick(eventData);
}

}
Run Code Online (Sandbox Code Playgroud)

和编辑类:

PS ButtonEditor与UnityEditor.UI.ButtonEditor不同,因为第一个来自UnityEngine.ButtonEditor.要从UnityEditor访问.UI,您需要将Editor脚本放在Editor文件夹下

using UnityEngine;
using UnityEditor;
using UnityEngine.UI;
using System.Collections;

[CustomEditor(typeof(UISegmentedControlButton))]
public class UISegmentedControlButtonEditor : UnityEditor.UI.ButtonEditor {


public override void OnInspectorGUI() {

    UISegmentedControlButton component = (UISegmentedControlButton)target;

    base.OnInspectorGUI();

    component.onSprite = (Sprite)EditorGUILayout.ObjectField("On Sprite", component.onSprite, typeof(Sprite), true);
    component.onTextColor = EditorGUILayout.ColorField("On text colour", component.onTextColor);
    component.offSprite = (Sprite)EditorGUILayout.ObjectField("Off Sprite", component.offSprite, typeof(Sprite), true);
    component.offTextColor = EditorGUILayout.ColorField("Off text colour", component.offTextColor);

}
}
Run Code Online (Sandbox Code Playgroud)

此处还有一个直接与Unity UI源有用的链接

https://bitbucket.org/Unity-Technologies/ui/src

并证明它有效:

在此输入图像描述

  • 谢谢.现在它有效.只是忘了将脚本移动到编辑器文件夹;)但是没有办法像转换组件一样直接扩展组件,这样我就可以使用默认按钮了吗? (3认同)