10. 实体管理与场景管理
10-1. 实体管理与场景管理
实体、场景、lua、声音等管理逻辑一样:1、xxxManager在Unity中管理这些模块,包括在Hierarchy中获取分组等,xxxManager最重要的作用是当gamestart.cs打开main.bytes执行的时候,给main.bytes提供接口(OpenUI等);2、xxxLogic运行该模块的逻辑,该模块只有框架,核心部分的实现都在xx.lua中实现,比如Update映射到lua的OnUpdate
实体管理部分:
在Scripts/Framework/Manager中创建EntityManager,Scripts/Framework/Behaviour中创建EntityLogic
private static EntityManager _entity;
public static EntityManager Entity
{
get {
return _entity; }
}
private static MySceneManager _scene;
public static MySceneManager Scene
{
get {
return _scene; }
}
public void Awake()
{
_resource = this.gameObject.AddComponent<ResourceManager>();
_lua = this.gameObject.AddComponent<LuaManager>();
_ui = this.gameObject.AddComponent<UIManager>();
_entity = this.gameObject.AddComponent<EntityManager>();
_scene = this.gameObject.AddComponent<MySceneManager>();
}
添加Root-Entity节点
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EntityManager : MonoBehaviour
{
//缓存实体
Dictionary<string, GameObject> m_Entities = new Dictionary<string, GameObject>();
//缓存实体分组的transform
Dictionary<string, Transform> m_Groups = new Dictionary<string, Transform>();
private Transform m_EntityParent;
private void Awake()
{
m_EntityParent = this.transform.parent.Find("Entity");
}
/// <summary>
/// 给Lua提供接口,方便添加实体分组
/// </summary>
/// <param name="groups">要添加的UI层级名称的list</param>
public void SetEntityGroup(List<string> groups)
{
for (int i = 0; i < groups.Count; i++)
{
GameObject group = new GameObject("Group-" + groups[i]);
group.transform.SetParent(m_EntityParent, false);
m_Groups[groups[i]] = group.transform;
}
}
/// <summary>
/// 返回指定层级的transform
/// </summary>
/// <param name="group">分组名称</param>
/// <returns>返回字典中对应分组名称的transform</returns>
Transform GetGroup(string group)
{
if (!m_Groups.ContainsKey(group))
{
Debug.LogError("group is not exist");
}
return m_Groups[group];
}
/// <summary>
/// 传入一个实体名字和lua名字,自动给ui预制体绑定C#脚本,自动执行lua脚本
/// </summary>
/// <param name="name">实体名字</param>
/// <param name="luaName">lua名字</param>
public void ShowEntity(string name, string group, string luaName)
{
GameObject entity = null;
//如果prefab已经加载过了(从ab包取出放到Dictionary中),就只执行OnShow(Start),不在执行Init(Awake)
if (m_Entities.TryGetValue(name, out entity))
{
EntityLogic logic = entity.GetComponent<EntityLogic>();
logic.OnShow();
return;
}
Manager.Resource.LoadPrefab(name, (UnityEngine