107 lines
3.7 KiB
C#
107 lines
3.7 KiB
C#
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using Base;
|
||
using Prefab;
|
||
using UnityEngine;
|
||
|
||
namespace Managers
|
||
{
|
||
public class EntityManage:Utils.MonoSingleton<EntityManage>,ITick
|
||
{
|
||
public Dictionary<string, List<EntityPrefab>> factionEntities = new();
|
||
|
||
public GameObject entityLevel;
|
||
public EntityPrefab entityPrefab;
|
||
|
||
public void Tick()
|
||
{
|
||
foreach (var faction in factionEntities)
|
||
{
|
||
List<EntityPrefab> entitiesToRemove = new List<EntityPrefab>();
|
||
|
||
foreach (var entityPrefab in faction.Value)
|
||
{
|
||
if (entityPrefab.entity.IsDead)
|
||
{
|
||
entitiesToRemove.Add(entityPrefab);
|
||
}
|
||
else
|
||
{
|
||
ITick itike = entityPrefab.entity;
|
||
itike.Tick();
|
||
}
|
||
}
|
||
|
||
// 删除所有标记为死亡的实体
|
||
foreach (var entityToRemove in entitiesToRemove)
|
||
{
|
||
faction.Value.Remove(entityToRemove);
|
||
Destroy(entityToRemove.gameObject);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 根据给定的PawnDef生成一个实体对象。
|
||
/// </summary>
|
||
/// <param name="pawnDef">定义实体属性的PawnDef对象。</param>
|
||
/// <param name="pos">实体生成的位置。</param>
|
||
/// <remarks>
|
||
/// 1. 如果entityPrefab或pawnDef为null,则不会生成实体。
|
||
/// 2. 实体将被创建在entityLevel.transform下。
|
||
/// 3. 使用EntityPrefab组件初始化实体。
|
||
/// </remarks>
|
||
public void GenerateEntity(Data.PawnDef pawnDef, Vector3 pos)
|
||
{
|
||
// 检查entityPrefab是否为空
|
||
if (entityPrefab == null)
|
||
{
|
||
Debug.LogError("Error: entityPrefab is null. Please assign a valid prefab.");
|
||
return;
|
||
}
|
||
|
||
// 检查pawnDef是否为空
|
||
if (pawnDef == null)
|
||
{
|
||
Debug.LogError("Error: PawnDef is null. Cannot generate entity without a valid PawnDef.");
|
||
return;
|
||
}
|
||
|
||
try
|
||
{
|
||
// 实例化实体对象
|
||
var entity = Instantiate(entityPrefab.gameObject, pos, Quaternion.identity, entityLevel.transform);
|
||
|
||
// 获取EntityPrefab组件
|
||
var entityComponent = entity.GetComponent<EntityPrefab>();
|
||
|
||
// 检查EntityPrefab组件是否存在
|
||
if (entityComponent == null)
|
||
{
|
||
Debug.LogError($"Error: EntityPrefab component not found on the instantiated object: {entity.name}");
|
||
return;
|
||
}
|
||
|
||
// 初始化实体组件
|
||
entityComponent.Init(pawnDef);
|
||
// 确保派系键存在,并初始化对应的列表
|
||
var factionKey = pawnDef.attributes.label == null ? "default" : pawnDef.attributes.label;
|
||
if (!factionEntities.ContainsKey(factionKey))
|
||
{
|
||
factionEntities[factionKey] = new List<EntityPrefab>();
|
||
}
|
||
factionEntities[factionKey].Add(entityComponent);
|
||
}
|
||
catch (System.Exception ex)
|
||
{
|
||
// 捕获并记录任何异常
|
||
Debug.LogError($"An error occurred while generating the entity: {ex.Message}");
|
||
}
|
||
}
|
||
|
||
protected override void OnStart()
|
||
{
|
||
factionEntities.Clear();
|
||
}
|
||
}
|
||
} |