unity布局管理器
使用unity布局管理器轻松对关卡选择进行布局。
实现过程
- 准备普通按钮button设置字体和对应的sprite
- 设置父gameobject(levelbase) 再创建UI.image(selectbackground)布局背景和大小
- gameobject(gridcontent)添加 grid layout group(布局)组件和content size fitter组件(控制布局内按钮拉伸)
- 将准备的按钮置于gameobject的子类
- 给布局背景添加rectmask2D属性,可以遮盖多余的
-
给父类levelbase添加scroll rect组件,并将gridcontent放入其content属性下,将levelbackground设置在viewport属性下
-
levelbase设置脚本
用于读取关卡信息设置按钮的是否可以交互状态
using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;public class ButtonIcons : MonoBehaviour
{[SerializeField] private Button[] lvlButton;[SerializeField] private Sprite unlockedIcon;[SerializeField] private Sprite lockedIcon;[SerializeField] private int firstLevelBuildIndex;// Start is called before the first frame updateprivate void Awake(){int unlockedLvL = PlayerPrefs.GetInt(EndGameManager.endManager.lvlUnlock, firstLevelBuildIndex);for(int i=0;i<lvlButton.Length; i++){if (i + firstLevelBuildIndex <= unlockedLvL){lvlButton[i].interactable = true;lvlButton[i].image.sprite = unlockedIcon;TextMeshProUGUI textButton = lvlButton[i].GetComponentInChildren<TextMeshProUGUI>();textButton.text = (i + 1).ToString();textButton.enabled = true;}else{lvlButton[i].interactable = false;lvlButton[i].transition = 0;lvlButton[i].transform.Find("Image").gameObject.SetActive(true);lvlButton[i].GetComponentInChildren<TextMeshProUGUI>().enabled = false;}}}
}