做到一个选中状态切换的需求,就是A按钮对应A面板,B按钮对应B面板,只能有一个面板为true,这时候需要在为true的面板对应的按钮上加个框框框选起来表明当前是哪个面板。我的思路就是获取到点击按钮的信息,然后将框框对应的prefab放在那个按钮下。研究了下获取点击到的UI的信息。做下笔记:
首先需要using UnityEngine.EventSystems; 引用这个,EventSystem.current.currentSelectedGameObject然后这个就是你点击的UI啦~
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class UIBeChoosedState : MonoBehaviour
{
public List<Button> Buttons;
public GameObject EdgeObj;
void OnEnable()
{
foreach(Button btn in Buttons)
{
btn.onClick.AddListener(ChangeChoosedState);
}
}
/// <summary>
/// 切换按钮选中状态时调用
/// </summary>
private void ChangeChoosedState()
{
GameObject clickedBtn = EventSystem.current.currentSelectedGameObject;
EdgeObj.transform.parent = clickedBtn.transform;
EdgeObj.transform.localPosition = Vector3.zero;
//Debug.Log(EventSystem.current.currentSelectedGameObject.name);
}
}
本文介绍了一个Unity项目中实现UI按钮选中状态切换的方法。通过监听按钮点击事件,并使用EventSystem来确定被点击的按钮,进而更新一个视觉提示元素(如边框),以指示当前选中的面板。
 获取到被点击的UI的信息&spm=1001.2101.3001.5002&articleId=78038222&d=1&t=3&u=dcde7ac0d3124d6caa5499c5999af963)
1万+

被折叠的 条评论
为什么被折叠?



