unity3d 如何在Unity 3D中使UI按钮保持按下状态

v64noz0r  于 2022-12-04  发布在  其他
关注(0)|答案(3)|浏览(751)

在Unity 3D中,当你选择一个按钮时,它将保持按下状态,直到你点击按钮外部,并基本上回到它的正常颜色。问题是,我希望当我点击按钮或场景外部时,按钮保持按下状态(颜色方面)。有人知道如何在点击按钮后保持按钮按下或“选中”吗?

bxpogfeg

bxpogfeg1#

您可以使用Unity UI Toggle(正如Muhammad所说)。更改设计以删除复选标记,使其看起来像一个按钮。使用此组件,您可以使用状态“isOn”,并在选择时更改颜色。

dbf7pr2w

dbf7pr2w2#

public class Button_Stay_Pressed : MonoBehaviour
{
    private Button btn;

    [SerializeField]
    private Sprite normal_sprite;
    [SerializeField]
    private Sprite pressed_sprite;

    void Awake()
    {
        btn = gameObject.GetComponent<Button>();
        btn.image.sprite = normal_sprite;
        btn.onClick.AddListener(TaskOnClick);
    }

    void TaskOnClick()
    {
        btn.image.sprite = pressed_sprite;
    }
}
iqih9akk

iqih9akk3#

以下是使用委托的C#脚本,该脚本将(在按钮之间切换)将单击的按钮设置为“on/pressed”(自定义)颜色,并更改附加了此脚本的其他按钮以取消选择颜色,复制和粘贴解决方案(将此脚本附加到您要切换的按钮):

using TMPro;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Functionality: Control UI Button clicks selected colour
/// Author: Akrima Huzaifa
/// Date Created: 1st-December-2022
/// </summary>

public class BtnClickHandler : MonoBehaviour
{
 public delegate void OnBtnClick(BtnClickHandler obj);
 public static event OnBtnClick onBtnClick;
 public Button poleBtn;
 public Image poleImage;

 private void Awake()
 {
     if (GetComponent<Button>())
     {
         poleBtn = GetComponent<Button>();
         poleImage = GetComponent<Image>();
         poleBtn.onClick.AddListener(delegate { OnBtnClick(); });
     }
 }

 private void OnEnable()
 {
     onBtnClick += SelectDeselectBtn;
 }

 private void OnDisable()
 {
     onBtnClick -= SelectDeselectBtn;
 }

 public void SelectDeselectBtn(BtnClickHandler obj)
 {
     if (obj == this)
     {
         OnClick_ObjButtonSelected();
     }
     else
     {
         DeselectBtn();
     }
 }

 public void OnBtnClick()
 {
     BtnClickHandler.onBtnClick.Invoke(this);
 }

 //---For UI---
 public void OnClick_ObjButtonSelected()
 {
     if (!poleImage.fillCenter)
     {
         print("if color");
         poleImage.fillCenter = true;
         poleImage.color = new Color32(230, 230, 230, 255);
         poleImage.transform.GetComponentInChildren<TextMeshProUGUI>().color = new Color32(255, 115, 0, 255);
     }
     else
     {
         DeselectBtn();
     }
 }

 public void DeselectBtn()
 {
     print("else color");
     poleImage.fillCenter = false;
     poleImage.color = new Color32(178, 178, 178, 255);
     poleImage.transform.GetComponentInChildren<TextMeshProUGUI>().color = new Color32(255, 255, 255, 255);
 }
}

相关问题