实现通用的UI布局
|Word count:482|Reading time:1min|Post View:
前言
为什么要实现通用的UI布局?
因为作为对美术一窍不通的程序员,并不想花太多时间去精致的摆放每一个UI,不如直接用锚点,看着太差不差就好了。
但是每次调整Unity锚点时都需要重新设置位置,真的很麻烦,干脆写个脚本,实现在运行时通过滑块调整UI布局。

通用的UI布局
何为通用的UI布局?
在我眼里就是网页设计中标准的,页头,正文和页脚三元素(其实就是一分为三块),想要多一点块就不断的嵌套,想要少一点块就将某几块的高度设为0.
于是就可以实现以下这样的PageLayout类。
- 在Awake时获取三元素的初始数据。
- 然后在Update时根据滑块数据不断的调整锚点位置。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| namespace UI { public class PageLayout : MonoBehaviour { private void Awake() { #if DEBUG _headerRectTransform = gameObject.transform.GetChild(0).gameObject.GetComponent<RectTransform>(); _contentRectTransform = gameObject.transform.GetChild(1).gameObject.GetComponent<RectTransform>(); _footerRectTransform = gameObject.transform.GetChild(2).gameObject.GetComponent<RectTransform>();
headerHeightPercent = 1f - _headerRectTransform.anchorMin.y; footerHeightPercent = _footerRectTransform.anchorMax.y; #endif }
private void Update() { #if DEBUG _headerRectTransform.anchorMin = new Vector2(0f, 1f - headerHeightPercent); _headerRectTransform.anchorMax = new Vector2(1f, 1f);
_contentRectTransform.anchorMin = new Vector2(0f, footerHeightPercent); _contentRectTransform.anchorMax = new Vector2(1f, 1f - headerHeightPercent);
_footerRectTransform.anchorMin = new Vector2(0f, 0f); _footerRectTransform.anchorMax = new Vector2(1f, footerHeightPercent); #endif }
#if DEBUG [Range(0f, 1f)] public float headerHeightPercent; [Range(0f, 1f)] public float footerHeightPercent; private RectTransform _headerRectTransform; private RectTransform _contentRectTransform; private RectTransform _footerRectTransform; #endif } }
|
滑着滑着,伴随着“嗯”的一声,一种恰到好处的感觉油然而生,那就拷贝一下数据然后复制就哦了,从未想过原来布局如此简单。
通过添加InputSystemUIInputModule,同时在EventSystem里设置FirstSelected就可以实现。

但是有个问题就是这样的话游戏一启动就会有一个按钮进入被选择的状态,感觉有点奇怪,应该可以通过设置一个隐形UI解决。