Co-authored-by: zzdxxz <2079238449@qq.com> Co-committed-by: zzdxxz <2079238449@qq.com>
78 lines
2.4 KiB
C#
78 lines
2.4 KiB
C#
using System;
|
|
using AI;
|
|
using Base;
|
|
using Data;
|
|
using Entity;
|
|
using Unity.VisualScripting;
|
|
using UnityEngine;
|
|
|
|
namespace Prefab
|
|
{
|
|
public class EntityPrefab : MonoBehaviour
|
|
{
|
|
public Entity.Entity entity;
|
|
public Outline outline;
|
|
|
|
|
|
public void Init(Data.PawnDef pawnDef)
|
|
{
|
|
entity.runtimeAttributes = pawnDef.attributes.Clone();
|
|
entity.aiTree = ConvertToAIBase(pawnDef.behaviorTree);
|
|
|
|
outline.Init();
|
|
outline.Hide();
|
|
}
|
|
public static AIBase ConvertToAIBase(BehaviorTreeDef behaviorTreeDef)
|
|
{
|
|
if (behaviorTreeDef == null)
|
|
return null;
|
|
AIBase aiBase = CreateAIBaseInstance(behaviorTreeDef.className);
|
|
if (behaviorTreeDef.childTree != null)
|
|
{
|
|
foreach (var child in behaviorTreeDef.childTree)
|
|
{
|
|
if (child != null)
|
|
{
|
|
aiBase.children.Add(ConvertToAIBase(child));
|
|
}
|
|
}
|
|
}
|
|
return aiBase;
|
|
}
|
|
|
|
// 使用反射根据 className 创建具体的 AIBase 子类实例
|
|
private static AIBase CreateAIBaseInstance(string className)
|
|
{
|
|
if (string.IsNullOrEmpty(className))
|
|
throw new ArgumentException("className 不能为空");
|
|
|
|
// 定义可能的命名空间列表
|
|
var possibleNamespaces = new[] { "AI"};
|
|
|
|
foreach (var ns in possibleNamespaces)
|
|
{
|
|
try
|
|
{
|
|
// 获取当前程序集
|
|
var assembly = typeof(AIBase).Assembly;
|
|
|
|
// 尝试查找类型
|
|
var type = assembly.GetType($"{ns}.{className}");
|
|
|
|
if (type != null && typeof(AIBase).IsAssignableFrom(type))
|
|
{
|
|
// 如果找到合适的类型,则创建实例并返回
|
|
return (AIBase)Activator.CreateInstance(type);
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
// 忽略单个命名空间的错误,继续尝试下一个命名空间
|
|
}
|
|
}
|
|
|
|
// 如果所有命名空间都未找到对应的类型,抛出异常
|
|
throw new InvalidOperationException($"无法找到类型 {className} 或该类型不是 AIBase 的子类");
|
|
}
|
|
}
|
|
} |