做到一个选中状态切换的需求,就是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);
}
}