using System.Collections;
using System.Collections.Generic;
using UnityEngine;
publicinterfaceIGameManager
{
ManagerStatus status { get; } //这是一个我们需要定义的枚举voidStartup(); //这个方法的目的是处理管理器的初始化
}
ManagerStatus的脚本代码
publicenumManagerStatus
{
Shutdown, //关机
Initializing, //正在初始化
Started //开始启动
}
PlayerManager的脚本代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///<summary>///人物管理脚本///</summary>publicclassPlayerManager : MonoBehaviour, IGameManager//继承一个类并实现一个接口
{
public ManagerStatus status
{
get;
privateset; //status只读,不能在外部设置,内部可读写
}
publicint health //人物健康值
{
get;
privateset;
}
publicint maxHealth //人物最高健康值
{
get;
privateset;
}
publicvoidStartup()
{
Debug.Log("PlayerManager starting ...");
health = 50; //初始化值
maxHealth = 100;
status = ManagerStatus.Started;
}
publicvoidChangeHealth(intvalue)
{
health += value;
if (health > maxHealth)
{
health = maxHealth;
}
elseif (health < 0) //健康值最小为0
{
health = 0;
}
Debug.Log("Health:" + health + "/" + maxHealth);
}
}
InventoryManager的脚本代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///<summary>///库存管理脚本///</summary>publicclassInventoryManager : MonoBehaviour, IGameManager
{
public ManagerStatus status //这个属性可以从任何地方获取,但只能在这个脚本中设置
{
get;
privateset;
}
publicvoidStartup()
{
Debug.Log("InventoryManager starting ...");//任何长任务在这里启动
status = ManagerStatus.Started; //如果是长任务,状态改变为"Initializing"
}
}
Managers的脚本代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///<summary>///管理器的管理器///</summary>
[RequireComponent(typeof(PlayerManager))] //自动添加管理器,确保存在不同的管理器
[RequireComponent(typeof(InventoryManager))]
publicclassManagers : MonoBehaviour
{
publicstatic PlayerManager Player //其他代码用来访问管理器的静态属性
{
get;
privateset;
}
publicstatic InventoryManager Inventory
{
get;
privateset;
}
private List<IGameManager> _startSequence; //启动时要遍历的管理器列表voidAwake() //列出了启动序列,然后启动协同程序来运行所有的管理器
{
Player = GetComponent<PlayerManager>();
Inventory = GetComponent<InventoryManager>();
_startSequence = new List<IGameManager>(); //创建了List对象,用List.Add的方法来添加管理器。列表对象与数组相似,以一种具体的类型声明,把一系列元素依次存入,但可在创建后改变大小。
_startSequence.Add(Player);
_startSequence.Add(Inventory);
StartCoroutine(StartupManagers()); //异步启动序列
}
private IEnumerator StartupManagers()
{
foreach (IGameManager manager in _startSequence)
{
manager.Startup();
}
yieldreturnnull;
int numModules = _startSequence.Count;
int numReady = 0;
while (numReady < numModules) //循环至所有管理器都启动为止
{
int lastReady = numReady;
numReady = 0;
foreach (IGameManager manager in _startSequence)
{
if (manager.status == ManagerStatus.Started)
{
numReady++;
}
}
if (numReady > lastReady)
Debug.Log("progress:" + numReady + "/" + numModules);
yieldreturnnull;
}
Debug.Log("All managers started up");
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步