微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

自定义Unity Editor中GUI按钮的颜色更改明显延迟

如何解决自定义Unity Editor中GUI按钮的颜色更改明显延迟

当我尝试在Unity Editor中使GUI按钮在悬停时更改颜色时,颜色更改成功但被严重延迟。这是鼠标悬停在按钮上时其活动的gif图像:

gif of the button changing color slowly when hovered

如您所见,颜色变化明显延迟。我需要找到一种方法,将其加速到鼠标一按下按钮就更改颜色的位置

这是重现该示例所需的最少代码。首先,用于创建编辑器的空类:

using UnityEngine;
public class Test : MonoBehavIoUr
{
   
}

然后,用于创建按钮的自定义编辑器:

using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(Test))]
public class TestEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        GUIStyle style = new GUIStyle()
        {
            alignment = TextAnchor.MiddleCenter,fontStyle = FontStyle.Bold,normal = new GUIStyleState()
            {
                background = Texture2D.whiteTexture
            },hover = new GUIStyleState()
            {
                background = Texture2D.grayTexture
            },active = new GUIStyleState()
            {
                background = Texture2D.blackTexture
            }
        };

        GUILayout.Button("Hello!",style);
    }
}

如果将此空的“ Test”类附加到Unity场景中的GameObject,则应该在帖子顶部显示编辑器。

是否有一些变通办法可以使此颜色更改更快,响应速度更快?任何建议,我们将不胜感激!

解决方法

您可以通过调用Repaint()来强制重绘Inspector窗口。最快的方法是使用延迟为100ms的Task,如下所示:

[CustomEditor ( typeof ( Test ) )]
public class TestEditor : Editor
{
    GUIStyle style;
    private bool repaint;

    private void Awake ( )
    {
        style = new GUIStyle ( )
        {
            alignment = TextAnchor.MiddleCenter,fontStyle = FontStyle.Bold,normal = new GUIStyleState ( ) { background = Texture2D.whiteTexture },hover = new GUIStyleState ( ) { background = Texture2D.grayTexture },active = new GUIStyleState ( ) { background = Texture2D.blackTexture }
        };

        repaint = true;
        Repainter ( );
    }

    private void OnDisable ( )
    {
        Debug.Log ( "repaint = false" );
        repaint = false;
    }

    async void Repainter ( )
    {
        while ( repaint )
        {
            this.Repaint ( );
            await Task.Delay ( 100 );
        }
    }

    public override void OnInspectorGUI ( )
    {
        base.OnInspectorGUI ( );
        GUILayout.Button ( "Hello!",style );
    }
}

我还想指出,我不一定建议这样做,但这应该不会造成伤害。而且只有在检查器窗口可见时才打开和关闭它。如果您可以进一步增加延迟前夜,直到您达到可接受的响应行为,我认为对每个参与人员来说都会更好。

EditorWindow也每秒更新10次。这样看来,Unity自己对每秒刷新一次窗口的数量感到非常满意。 Unity文档:EditorWindow.OnInspectorUpdate

这应该为您提供一个快照器检查器按钮。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。