首页 > 解决方案 > 如何使用按钮索引为特定单击的按钮着色?

问题描述

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using UnityEditor;
using UnityEngine;
using System.IO;

public class Manager : EditorWindow
{
    private static bool red;

    [MenuItem("Tools/Manager")]
    static void Managers()
    {
        EditorWindow.GetWindow<Manager>();
        Init();
    }

    private static void Init()
    {
        red = true;
    }

    private void OnGUI()
    {
        GUIContent c = new GUIContent();

        var style = new GUIStyle(GUI.skin.button);

        if (red)
        {
            style.normal.textColor = Color.red;
        }
        else
        {
            style.normal.textColor = Color.green;
        }
        style.fontSize = 18;

        string[] Paths = new string[2];
        string[0] = "testing1";
        string[1] = "testing2";

        for (int i = 0; i < Paths.Length; i++)
        {
            if (Paths[i].Contains("test")) // or .js if you want
            {
                var x = assetPaths[i].LastIndexOf("/");
                var t = assetPaths[i].Substring(x + 1);

                GUILayout.Button(t, style, GUILayout.Width(1000), GUILayout.Height(50));
                if (Event.current.type == EventType.Repaint && GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition))
                {
                    OnMouseOver(i);
                }
            }
        }
    }

    private void OnMouseOver(int buttinIndex)
    {
        UnityEngine.Debug.LogFormat("OnMouseOver {0}", buttinIndex);
        red = !red;
    }
}

问题是当我将鼠标光标移到其中一个按钮上时,它会将所有按钮都涂成绿色,然后又变回红色。

我希望当我单击特定按钮或将鼠标光标移动到特定按钮颜色上时,仅此按钮为绿色并将按钮保留为绿色。

标签: c#unity3d

解决方案


您应该使用 List 或其他方式记录每个按钮的样式。

目前,您的代码导致所有按钮都使用相同的样式,因此它们会一起更改。

我提供小费。我希望这可以帮助你。

private void OnMouseOver(int buttinIndex)
{
    UnityEngine.Debug.LogFormat("OnMouseOver {0}", buttinIndex);
    //red = !red; 
    //try to record style or color flag for each button use index.
}

当你画按钮

GUILayout.Button(t, GetStyleFromList(i), GUILayout.Width(1000), GUILayout.Height(50));

推荐阅读