88 lines
3.2 KiB
C#
88 lines
3.2 KiB
C#
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using Prefab;
|
||
using UnityEngine;
|
||
|
||
namespace Managers
|
||
{
|
||
public class EntityManage:MonoBehaviour
|
||
{
|
||
public Dictionary<string, List<EntityPrefab>> factionEntities = new();
|
||
|
||
public GameObject entityLevel;
|
||
public EntityPrefab entityPrefab;
|
||
void Update()
|
||
{
|
||
// 检测鼠标左键是否按下
|
||
if (Input.GetMouseButtonDown(0))
|
||
{
|
||
var ray = Camera.main.ScreenPointToRay(Input.mousePosition); // 获取从相机发出的射线
|
||
|
||
if (Physics.Raycast(ray, out var hit)) // 检测射线是否击中物体
|
||
{
|
||
Debug.Log("点击了物体: " + hit.collider.gameObject.name);
|
||
|
||
}
|
||
}
|
||
}
|
||
/// <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);
|
||
|
||
Base.Clock.AddTick(entity.GetComponent<Entity.Entity>());
|
||
}
|
||
catch (System.Exception ex)
|
||
{
|
||
// 捕获并记录任何异常
|
||
Debug.LogError($"An error occurred while generating the entity: {ex.Message}");
|
||
}
|
||
}
|
||
}
|
||
} |