owned this note
owned this note
Published
Linked with GitHub
# FairyGUI+遊戲腳本設計 - UIManager腳本(下集)
BasePanel跟UIPanelType建立好後,UIM腳本來負責「切換」頁面。
UIM是切換頁面的管理者,頁面又分為「主頁面場景」跟「遊戲場景」。所以UIM內也切分這兩個部份。
1、UIM內會判斷現在是在「主頁面場景」,還是「遊戲場景」。
2、並且,UIM內會建立**字典**。字典用來查找panel的種類(哪一種UIPanelType)、以及panel的名稱。
3、UIM負責切換頁面,所以切換時,會先查找字典,看是否還有內容在字典內,因為切換panel時要把上一個頁面的內容從字典內清除。所以要建立清除函式ClearDict()。
4、實例化主頁面。主頁面繼承BP,所以要先寫好BP。
5、實例化遊戲頁面。遊戲頁面繼承GameBasePanel,所以要先寫好GBP。
```C#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIMananger
{
public bool isGameUIManager; //判斷是否在遊戲UI,還是在主頁面UI
public Dictionary<UIPanelType, BasePanel> UIPanelDict; //在字典裡查找,進行顯示隱藏或移除
public UIManager() //UIM實例化後,字典也實例化了
UIPanelDict = new Dictionary<UIPanelType, BasePanel>();
}
//清空字典的方法
//切換頁面時,要清除BasePanel裡面的內容,所以要清空字典
public void ClearDict()
{
foreach (var item in UIPanelDict)
{ ////BP是從window(FGUI的一種class)繼承,要從字典內刪除得用Dispose()
item.Value.Dispose();//GM加載場景不銷毀,用FGUI的方法去銷毀對象
}
UIPanelDict.Clear();
}
//要進去遊戲場景內,就由GameUIManager這函式來處理。
//要進去遊戲場景內,就實例化每個遊戲場景。
public void GameUIManager()
{
isGameUIManager = true;
if (UIPanelDict.Count!=0)
{
ClearDict();
}
//實例化對象
//這邊用遊戲場景ABC來舉例
//可以翻譯成:以GameBasePanel作為基類,新產生GamePanel,參數分別是"名字"、"枚舉類的種類"、"UIManager"
GameBasePanel gameAPanel = new GameAPanel("GameAPanel",UIPanelType.GameAPanel,this);
GameBasePanel gameBPanel = new GameBPanel("GameBPanel",UIPanelType.GameBPanel,this);
GameBasePanel gameCPanel = new GameCPanel("GameCPanel", UIPanelType.GameCPanel, this);
//函式責任鍊,一種C#的設計模式
//如果遊戲是屬於一頁接著一頁才用到
//好比說遊戲畫面A接著遊戲畫面B....到遊戲畫面F
GameAPanel.SetNextPanel(GameBPanel).SetNextPanel(GameCPanel)
.SetNextPanel(GameDPanel).SetNextPanel(GameEPanel)
.SetNextPanel(GameFPanel);
//實例化後,並在字典內添加這些資料
//這邊用遊戲場景ABC來舉例
//字典用來查找panel的種類(哪一種UIPanelType)、以及panel的名稱。
UIPanelDict.Add(UIPanelType.GameAPanel, gameAPanel);
UIPanelDict.Add(UIPanelType.GameBPanel, gameBPanel);
UIPanelDict.Add(UIPanelType.GameCPanel, gameCPanel);
//跟GBP說,第一個遊戲畫面先顯示
//這邊是載入畫面
UIPanelDict[UIPanelType.GameAPanel].Show();
//跟GBP聲明,它就是第一個頁面,並且進入
//這邊是進入場景,所以不只畫面,資訊也都載入
GameBasePanel firstPanel = UIPanelDict[UIPanelType.GameAPanel] as GameBasePanel;
firstPanel.EnterPanel();
firstPanel.HandleGameAction(UIPanelType.GameAPanel);
}
//主頁面
//父類聲明,子類實例化的寫法
//意思是這邊先聲明,各個主頁面內自己去實例化自己
public void MainUIManager()
{
isGameUIManager = false; //不是遊戲頁面
if (UIPanelDict.Count != 0)
{
ClearDict(); //清空字典,裡面不能有其他頁面加載過的東西
}
UIPanelDict.Add(UIPanelType.MainPanel, new MainPanel("Panel_Main", UIPanelType.MainPanel, this));
UIPanelDict.Add(UIPanelType.GamePanel, new GamePanel("Panel_Game", UIPanelType.GamePanel, this));
UIPanelDict.Add(UIPanelType.HelpPanel, new HelpPanel("Panel_Help", UIPanelType.HelpPanel, this));
UIPanelDict.Add(UIPanelType.SetPanel, new SetPanel("Panel_Set", UIPanelType.SetPanel, this));
UIPanelDict[UIPanelType.MainPanel].Show(); //主介面先顯示。用鍵來查找字典,再顯示。
}
}
```