在C# 集合类 :(Array、 Arraylist、List、Hashtable、Dictionary、Stack、Queue),我们知道了集合的基本用法,但有时我们需要记录更多的数据,就需要几个集合一起用。
我现在需要做一个警报列表的功能,每项报警码有它的标准提示语。而每项报警码可以有几种报警级别。
发出警报、警报更新、警报取消都要改变UI,因此每个报警码需要关联一个UI plane。
发出警报、警报更新时,旧的plane关闭,发出新的plane。
警报取消时,plane上显示的报警级别为0,但还有警报的plane要置顶,因此需要重新排序。
在脚本开头,我写了报警码的Class。
public class AlertCode
{
public string msg {
get; set; }
public int curRate {
get; set; }
public AlertPanelPlane curPlane {
get; set; }
//AlertPanelPlane 是每个plane自己的脚本,记录plane显示在的东西。
public int positionInArray {
get; set; }
}
然后创建Dictionary。Array List 和positionInArray 我后面再提。
Dictionary<string, AlertCode> alert_dict;
void Start()
{
activeAlert_array = new ArrayList();
alert_dict = new Dictionary<string, AlertCode>();
CreateDictionary();
}
public void CreateDictionary()
{
//举几个例子
AlertCode A03 = new AlertCode();
A03.msg = "1#发动机失电";
A03.curRate = 0;
A03.positionInArray = 0;
A03.curPlane = null;
alert_dict.Add("A03", A03);
AlertCode A04 = new AlertCode();
A04.msg = "1#发动机过载";
A04.curRate = 0;
A04.positionInArray = 0;
A04.curPlane = null;
alert_dict.Add("A04", A04);
AlertCode A05 = new AlertCode();
A05.msg = "1#发动机缺相";
A05.curRate = 0;
A05.positionInArray = 0;
A05.curPlane = null;
alert_dict.Add("A05", A05);
}
在有新消息的时候,传来的数据会包括报警码(code)和级别(rate)。
收到的Code 可以用在字典中找出其类里面的资料。
如果该Panel是Active的话,就把他加到activeAlert_array里,然后将对应的activeAlert_array.Count加到positionInArray 记录。
switch(rate)
{
case 1: //1级警报
case 2: //2级警报
AlertPanelPlane newPlane = Instantiate(alertPlane, alertPlaneParent);
newPlane.name = code.ToString();
newPlane.gameObject.SetActive(true);
newPlane.transform.SetAsFirstSibling();
newPlane.OnDetailsUpdated(rate, alert_dict[code].msg);
alert_dict[code].curRate = rate;
if(alert_dict[code].curPlane != null)
{
alert_dict[code].curPlane.gameObject.SetActive(false);
}
alert_dict[code].curPlane = newPlane;
activeAlert_array.Add(newPlane);
alert_dict[code].positionInArray = activeAlert_array.Count;
break;
case 0: //警报取消
AlertPanelPlane activePlane = alert_dict[code].curPlane;
if(activePlane != null)
{
activePlane.OnDetailsUpdated(rate, "");
alert_dict[code].curRate = 0;
}
alert_dict[code].curPlane = null;
activeAlert_array.RemoveAt(alert_dict[code].positionInArray - 1);
alert_dict[code].positionInArray = 0;
ResetActiveAlertPriority();
break;
default:
break;
}
}
取消警报时从activeAlert_array里移除该plane,然后将余下activeAlert_array内的plane重新进行一次置顶(SetAsFirstSibling)。
void ResetActiveAlertPriority()
{
for(int i = 0; i != activeAlert_array.Count; i++)
{
AlertPanelPlane panel = (AlertPanelPlane)activeAlert_array[i];
panel.transform.SetAsFirstSibling();
}
}
在这个例子中Dictionary负责搜索,Class负责在字典中提供对应Code的资料,ArrayList负责排序时的次序。