UI抽取思路
一款手机游戏中UI有几十个到上百个不等,如果一个一个做这些UI,无疑会花费很多时间。
近期我们的游戏UI已经是第N次改版了,经过这N多次的修改,我总结了UI其实有很多的共性(就是相同性)。
下面说一些我觉得常用的UI的抽取思路
共用按钮
共同点:按钮,标题,[图标],[消息数提醒]
思路分析
按钮点击事件和标题是一定有的,其它的视情况而定。所以我们可以创建一个类 BtnItemClass,用来处理UI的逻辑,外部就只要传入相应的参数就可
共用组件
using System;
using UnityEngine;
using System.Collections; /// <summary>
/// 共用的图文按钮,抽取类
/// 包括:商店,挑战,朋友,英雄
/// </summary>
public class BtnItemClass
{
public string TitleSprite;
public string IconSprite;
public string BtnName;
public string NextUITitle;
//按钮点击的事件
public UIEventListener.VoidDelegate Callback;
//消息提醒数
public string TipMsg;
public int TipNum;
private bool IsEnabled; /// <summary>
/// 构造函数
/// </summary>
/// <param name="btnName">按钮名</param>
/// <param name="iconSprite">Item 图标</param>
/// <param name="titleSprite">标题文字图片,没有就填null</param>
/// <param name="nextUiTitle">下一级UI的标题</param>
/// <param name="callback">点击的事件</param>
/// <param name="enabled"></param>
public BtnItemClass(string btnName, string iconSprite, string titleSprite, string nextUiTitle, UIEventListener.VoidDelegate callback, bool enabled = true)
{
this.BtnName = btnName;
this.IconSprite = iconSprite ?? "null";
this.TitleSprite = titleSprite ?? "null";
this.NextUITitle = nextUiTitle;
this.Callback = callback;
IsEnabled = enabled;
} public BtnItemClass()
{
}
//设置属性
public static void Bind(BtnItemClass itemClass, Transform trans)
{
if(!string.IsNullOrEmpty( itemClass.BtnName))
trans.name = itemClass.BtnName; //标题文字图片
UISprite titleSprite = CTool.GetChildComponent<UISprite>("TitleSprite", trans);
titleSprite.spriteName = itemClass.TitleSprite;
titleSprite.MakePixelPerfect(); //图标
UISprite iconSprite = CTool.GetChildComponent<UISprite>("IconSprite", trans);
iconSprite.spriteName = itemClass.IconSprite;
iconSprite.MakePixelPerfect(); //当标题图片找不到时就显示文字
var titleLabel = CTool.GetChildComponent<UILabel>("TitleLabel", trans);
if (string.IsNullOrEmpty(itemClass.TitleSprite)|| itemClass.TitleSprite == "null")
{
titleLabel.text = itemClass.NextUITitle;
titleLabel.gameObject.SetActive(true);
}
else
{
titleLabel.gameObject.SetActive(false);
} //绑定事件
trans.GetComponent<UIEventListener>().onClick = itemClass.Callback; //button.isEnabled = item.IsEnable = item.IsEnable;
}
}
使用方法
首先构建一个List,里面里包含当前的UI所有按钮的数据,然后做刷新UI(生成按钮,设置按钮属性)
//按钮数据
private List<BtnItemClass> UIConfigList
{
get
{
return new List<BtnItemClass>()
{ new BtnItemClass("BtnHeroList", "BattleTeam_icon_HeroStrong", "null", "英雄强化",
obj => CNetPlayer.CheckPackageOverflow_WithMsgBox(() => CUIHeroList.Show("英雄强化"))),
new BtnItemClass( "武器强化,obj => CUIPowerUp.ShowWeaponstSelectList()),
};
}
} //刷新UI
private void RefreshUI()
{
var max = UIConfigList.Count;
CUIHelper.ResizeCUITableGridGameObjects(TableGrid, max, CommPicBtnTemplate); for (int idx = ; idx < max; idx++)
{
var trans = TableGrid.transform.GetChild(idx);
var itemClass = UIConfigList[idx];
BtnItemClass.Bind(itemClass, trans);
} TableGrid.Reposition();
}