(client) feat:实现实体动态创建,实体右键菜单
Co-authored-by: m0_75251201 <m0_75251201@noreply.gitcode.com> Reviewed-on: Roguelite-Game-Developing-Team/Gen_Hack-and-Slash-Roguelite#41
This commit is contained in:
@ -8,7 +8,12 @@ namespace AI
|
||||
{
|
||||
public List<AIBase> children = new();
|
||||
|
||||
public virtual JobBase GetJob(Entity.Entity target)
|
||||
public abstract JobBase GetJob(Entity.Entity target);
|
||||
}
|
||||
|
||||
public class Selector : AIBase
|
||||
{
|
||||
public override JobBase GetJob(Entity.Entity target)
|
||||
{
|
||||
foreach (var aiBase in children)
|
||||
{
|
||||
@ -19,28 +24,7 @@ namespace AI
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public class ContinuousMove : AIBase
|
||||
{
|
||||
override public JobBase GetJob(Entity.Entity target)
|
||||
{
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public class TrackPlayer : AIBase
|
||||
{
|
||||
|
||||
}
|
||||
public class RandomWander : AIBase
|
||||
{
|
||||
public override JobBase GetJob(Entity.Entity target)
|
||||
{
|
||||
return new WanderJob();
|
||||
}
|
||||
}
|
||||
public class ConditionalAI : AIBase
|
||||
public class ConditionalAI : Selector
|
||||
{
|
||||
// 条件函数,返回 true 表示满足条件
|
||||
private Func<Entity.Entity, bool> condition;
|
||||
@ -64,4 +48,56 @@ namespace AI
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public class SequentialAI : Selector
|
||||
{
|
||||
private int currentIndex = 0; // 当前正在尝试的子节点索引
|
||||
|
||||
public override JobBase GetJob(Entity.Entity target)
|
||||
{
|
||||
// 如果当前索引超出了子节点范围,重置索引并返回 null
|
||||
if (currentIndex >= children.Count)
|
||||
{
|
||||
ResetIndex();
|
||||
return null;
|
||||
}
|
||||
|
||||
// 获取当前子节点的任务
|
||||
var currentChild = children[currentIndex];
|
||||
var job = currentChild.GetJob(target);
|
||||
|
||||
// 移动到下一个子节点
|
||||
currentIndex++;
|
||||
|
||||
return job;
|
||||
}
|
||||
|
||||
// 重置当前索引(用于重新开始遍历)
|
||||
private void ResetIndex()
|
||||
{
|
||||
currentIndex = 0;
|
||||
}
|
||||
}
|
||||
public class ContinuousMove : AIBase
|
||||
{
|
||||
public override JobBase GetJob(Entity.Entity target)
|
||||
{
|
||||
return new MoveJob();
|
||||
}
|
||||
}
|
||||
|
||||
public class TrackPlayer : AIBase
|
||||
{
|
||||
public override JobBase GetJob(Entity.Entity target)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
public class RandomWander : AIBase
|
||||
{
|
||||
public override JobBase GetJob(Entity.Entity target)
|
||||
{
|
||||
return new WanderJob();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -7,7 +7,7 @@ namespace AI
|
||||
public abstract class JobBase
|
||||
{
|
||||
public Entity.Entity entity;
|
||||
private int timeoutTicks = 100;
|
||||
protected int timeoutTicks = 300;
|
||||
public bool Running=>timeoutTicks > 0;
|
||||
|
||||
public virtual void StartJob(Entity.Entity target)
|
||||
@ -57,5 +57,22 @@ namespace AI
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public class IdleJob:JobBase
|
||||
{
|
||||
override public void StartJob(Entity.Entity target)
|
||||
{
|
||||
base.StartJob(target);
|
||||
timeoutTicks = 500;
|
||||
}
|
||||
protected override void UpdateJob()
|
||||
{
|
||||
}
|
||||
}
|
||||
public class MoveJob : JobBase
|
||||
{
|
||||
protected override void UpdateJob()
|
||||
{
|
||||
entity.TryMove();
|
||||
}
|
||||
}
|
||||
}
|
@ -105,5 +105,40 @@ namespace Base
|
||||
if (obj is ITickUI uiObj) tickUIs.Add(uiObj);
|
||||
}
|
||||
}
|
||||
public static void AddTick(ITick tick)
|
||||
{
|
||||
if (Instance != null && !Instance.ticks.Contains(tick))
|
||||
Instance.ticks.Add(tick);
|
||||
}
|
||||
|
||||
public static void RemoveTick(ITick tick)
|
||||
{
|
||||
if (Instance != null)
|
||||
Instance.ticks.Remove(tick);
|
||||
}
|
||||
|
||||
public static void AddTickPhysics(ITickPhysics physics)
|
||||
{
|
||||
if (Instance != null && !Instance.tickPhysics.Contains(physics))
|
||||
Instance.tickPhysics.Add(physics);
|
||||
}
|
||||
|
||||
public static void RemoveTickPhysics(ITickPhysics physics)
|
||||
{
|
||||
if (Instance != null)
|
||||
Instance.tickPhysics.Remove(physics);
|
||||
}
|
||||
|
||||
public static void AddTickUI(ITickUI ui)
|
||||
{
|
||||
if (Instance != null && !Instance.tickUIs.Contains(ui))
|
||||
Instance.tickUIs.Add(ui);
|
||||
}
|
||||
|
||||
public static void RemoveTickUI(ITickUI ui)
|
||||
{
|
||||
if (Instance != null)
|
||||
Instance.tickUIs.Remove(ui);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Xml.Linq;
|
||||
@ -339,5 +340,53 @@ namespace Configs
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取指定目录下所有匹配后缀名的文件路径(可递归)
|
||||
/// </summary>
|
||||
/// <param name="directoryPath">目标文件夹路径</param>
|
||||
/// <param name="extensions">后缀名列表(如 ["txt", "jpg"])</param>
|
||||
/// <param name="searchOption">是否包含子文件夹</param>
|
||||
/// <returns>匹配的文件路径列表</returns>
|
||||
public static List<string> GetFilesByExtensions(
|
||||
string directoryPath,
|
||||
string[] extensions,
|
||||
SearchOption searchOption = SearchOption.AllDirectories)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(directoryPath))
|
||||
throw new ArgumentException("目录路径不能为空", nameof(directoryPath));
|
||||
|
||||
if (!Directory.Exists(directoryPath))
|
||||
throw new DirectoryNotFoundException($"目录不存在: {directoryPath}");
|
||||
|
||||
if (extensions == null || extensions.Length == 0)
|
||||
throw new ArgumentException("后缀名列表不能为空", nameof(extensions));
|
||||
|
||||
// 标准化后缀名(去掉点,转小写)
|
||||
var normalizedExtensions = new HashSet<string>(
|
||||
extensions.Select(ext => ext.TrimStart('.').ToLower())
|
||||
);
|
||||
|
||||
var result = new List<string>();
|
||||
|
||||
try
|
||||
{
|
||||
var files = Directory.GetFiles(directoryPath, "*", searchOption);
|
||||
foreach (var file in files)
|
||||
{
|
||||
var ext = Path.GetExtension(file).TrimStart('.').ToLower();
|
||||
if (normalizedExtensions.Contains(ext))
|
||||
{
|
||||
result.Add(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
// 可选:记录日志或忽略无权限目录
|
||||
Console.WriteLine($"访问被拒绝: {ex.Message}");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
@ -28,54 +28,43 @@ namespace Data
|
||||
|
||||
public class DrawingOrderDef : Define
|
||||
{
|
||||
public List<DrawNodeDef> drawNodes = new();
|
||||
public override bool Init(XElement xmlDef)
|
||||
public DrawNodeDef drawingOrder_down;
|
||||
public DrawNodeDef drawingOrder_up;
|
||||
public DrawNodeDef drawingOrder_left;
|
||||
public DrawNodeDef drawingOrder_right;
|
||||
public string texturePath;
|
||||
|
||||
public DrawNodeDef GetDrawingOrder(Orientation orientation)
|
||||
{
|
||||
base.Init(xmlDef);
|
||||
// 定义一个临时变量用于存储结果
|
||||
DrawNodeDef result = null;
|
||||
|
||||
var nodes = xmlDef.Elements("DrawNodeDef");
|
||||
var xElements = nodes as XElement[] ?? nodes.ToArray();
|
||||
if (!xElements.Any())
|
||||
return false;
|
||||
foreach (var node in xElements)
|
||||
// 根据传入的 Orientation 获取对应的 DrawingOrderDef
|
||||
switch (orientation)
|
||||
{
|
||||
var drawNode = new DrawNodeDef();
|
||||
drawNode.Init(node);
|
||||
drawNodes.Add(drawNode);
|
||||
case Orientation.Down:
|
||||
result = drawingOrder_down;
|
||||
break;
|
||||
case Orientation.Up:
|
||||
result = drawingOrder_up;
|
||||
break;
|
||||
case Orientation.Left:
|
||||
result = drawingOrder_left;
|
||||
break;
|
||||
case Orientation.Right:
|
||||
result = drawingOrder_right;
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentException("Invalid orientation value.");
|
||||
}
|
||||
|
||||
return true;;
|
||||
}
|
||||
// 重载 == 运算符
|
||||
public static bool operator ==(DrawingOrderDef a, DrawingOrderDef b)
|
||||
{
|
||||
if (ReferenceEquals(a, b)) return true; // 如果是同一个对象,直接返回 true
|
||||
if (ReferenceEquals(a, null) || ReferenceEquals(b, null)) return false; // 如果其中一个为 null,返回 false
|
||||
// 如果当前方向的结果为空,则尝试用 drawingOrder_down 填充
|
||||
if (result == null) result = drawingOrder_down;
|
||||
|
||||
return AreEqual(a, b);
|
||||
}
|
||||
// 如果 drawingOrder_down 仍然为空,则尝试用其他非空方向填充
|
||||
if (result == null) result = drawingOrder_up ?? drawingOrder_left ?? drawingOrder_right;
|
||||
|
||||
// 重载 != 运算符
|
||||
public static bool operator !=(DrawingOrderDef a, DrawingOrderDef b)
|
||||
{
|
||||
return !(a == b);
|
||||
}
|
||||
|
||||
// 判断两个 DrawingOrderDef 是否相等
|
||||
private static bool AreEqual(DrawingOrderDef a, DrawingOrderDef b)
|
||||
{
|
||||
// 比较 drawNodes 的数量
|
||||
if (a.drawNodes.Count != b.drawNodes.Count)
|
||||
return false;
|
||||
|
||||
// 递归比较每个 DrawNodeDef
|
||||
for (int i = 0; i < a.drawNodes.Count; i++)
|
||||
{
|
||||
if (!DrawNodeDef.AreEqual(a.drawNodes[i], b.drawNodes[i]))
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
@ -91,14 +80,14 @@ namespace Data
|
||||
{
|
||||
base.Init(xmlDef);
|
||||
|
||||
nodeName = xmlDef.Attribute("name")?.Value;
|
||||
nodeName = xmlDef.Attribute("name")?.Value??"noName";
|
||||
drawNodeType = Enum.TryParse(xmlDef.Attribute("type")?.Value, true, out DrawNodeType typeResult)
|
||||
? typeResult
|
||||
: DrawNodeType.Image;
|
||||
|
||||
position = StringToVector(xmlDef.Attribute("position")?.Value ?? "(0 0)");
|
||||
FPS = float.TryParse(xmlDef.Attribute("FPS")?.Value, out float result) ? result : 1.0f;
|
||||
foreach (var childNode in xmlDef.Elements("DrawNodeDef"))
|
||||
foreach (var childNode in xmlDef.Elements())
|
||||
{
|
||||
var child = new DrawNodeDef();
|
||||
child.Init(childNode);
|
||||
|
@ -15,7 +15,7 @@ namespace Data
|
||||
public string label;
|
||||
public string packID;
|
||||
|
||||
public bool isReferene=false;
|
||||
public bool isReferene = false;
|
||||
|
||||
/// <summary>
|
||||
/// 初始化方法,根据传入的 XML 元素 (<paramref name="xmlDef" />) 进行处理。
|
||||
@ -50,69 +50,93 @@ namespace Data
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
|
||||
// 使用反射获取当前类的所有字段和属性
|
||||
var fieldsAndProperties = GetAllFieldsAndProperties(this);
|
||||
// 显示基类中的基本信息
|
||||
sb.AppendLine($"Define {{");
|
||||
sb.AppendLine($"\tdefName: {defName}");
|
||||
sb.AppendLine($"\tdescription: {description}");
|
||||
sb.AppendLine($"\tlabel: {label}");
|
||||
|
||||
foreach (var member in fieldsAndProperties)
|
||||
// 获取当前对象的所有字段
|
||||
var fields = GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
|
||||
|
||||
foreach (var field in fields)
|
||||
{
|
||||
var name = member.Name;
|
||||
var value = GetValue(member, this);
|
||||
if (field.Name == "defName" || field.Name == "description" || field.Name == "label")
|
||||
continue; // 已经显示过的基本信息跳过
|
||||
|
||||
if (value is IList list && list.Count > 0) // 如果是列表类型
|
||||
{
|
||||
sb.AppendLine($"{name}:");
|
||||
foreach (var item in list) sb.AppendLine($" - {FormatValue(item)}");
|
||||
}
|
||||
else if (value is Define defineObject) // 如果是继承自 Define 的子类
|
||||
{
|
||||
if (!string.IsNullOrEmpty(defineObject.defName))
|
||||
{
|
||||
sb.AppendLine($"{name}: {defineObject.defName}");
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.AppendLine($"{name}:");
|
||||
sb.AppendLine(Indent(defineObject.ToString(), " "));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.AppendLine($"{name}: {FormatValue(value)}");
|
||||
}
|
||||
sb.Append("\t");
|
||||
sb.Append(field.Name);
|
||||
sb.Append(": ");
|
||||
|
||||
AppendFieldInfo(sb, field.GetValue(this), "\t\t");
|
||||
|
||||
sb.AppendLine();
|
||||
}
|
||||
|
||||
sb.Append("}");
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static IEnumerable<MemberInfo> GetAllFieldsAndProperties(object obj)
|
||||
private void AppendFieldInfo(StringBuilder sb, object value, string indent)
|
||||
{
|
||||
var type = obj.GetType();
|
||||
return type.GetFields(BindingFlags.Public | BindingFlags.Instance)
|
||||
.Concat(type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Cast<MemberInfo>());
|
||||
}
|
||||
|
||||
private static object GetValue(MemberInfo member, object obj)
|
||||
{
|
||||
switch (member)
|
||||
if (value == null)
|
||||
{
|
||||
case FieldInfo field:
|
||||
return field.GetValue(obj);
|
||||
case PropertyInfo property:
|
||||
return property.GetValue(obj);
|
||||
default:
|
||||
throw new ArgumentException("Unsupported member type.");
|
||||
sb.Append("null");
|
||||
return;
|
||||
}
|
||||
|
||||
var type = value.GetType();
|
||||
|
||||
// 如果是简单类型(如 int, string, bool 等)
|
||||
if (type.IsPrimitive || type == typeof(string) || type == typeof(decimal))
|
||||
{
|
||||
sb.Append(value);
|
||||
}
|
||||
// 如果是集合类型(如 List<T>, Dictionary<K,V> 等)
|
||||
else if (typeof(IEnumerable).IsAssignableFrom(type) && !(value is string))
|
||||
{
|
||||
sb.AppendLine(" [");
|
||||
var isFirst = true;
|
||||
foreach (var item in (IEnumerable)value)
|
||||
{
|
||||
if (!isFirst)
|
||||
sb.AppendLine(",");
|
||||
isFirst = false;
|
||||
|
||||
sb.Append(indent);
|
||||
AppendFieldInfo(sb, item, indent + "\t");
|
||||
}
|
||||
|
||||
if (!isFirst) // 如果集合不为空,则添加逗号后的换行
|
||||
sb.AppendLine();
|
||||
sb.Append(indent.TrimEnd('\t')); // 回退一级缩进
|
||||
sb.Append("]");
|
||||
}
|
||||
// 如果是自定义对象类型
|
||||
else
|
||||
{
|
||||
sb.AppendLine(" {");
|
||||
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
|
||||
var isFirst = true;
|
||||
foreach (var field in fields)
|
||||
{
|
||||
if (!isFirst)
|
||||
sb.AppendLine(",");
|
||||
isFirst = false;
|
||||
|
||||
sb.Append(indent);
|
||||
sb.Append(field.Name);
|
||||
sb.Append(": ");
|
||||
AppendFieldInfo(sb, field.GetValue(value), indent + "\t");
|
||||
}
|
||||
|
||||
if (!isFirst) // 如果对象有字段,则添加逗号后的换行
|
||||
sb.AppendLine();
|
||||
sb.Append(indent.TrimEnd('\t')); // 回退一级缩进
|
||||
sb.Append("}");
|
||||
}
|
||||
}
|
||||
|
||||
private static string FormatValue(object value)
|
||||
{
|
||||
return value?.ToString() ?? "null";
|
||||
}
|
||||
|
||||
private static string Indent(string text, string prefix)
|
||||
{
|
||||
return string.Join(Environment.NewLine, text.Split('\n').Select(line => prefix + line));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -1,8 +1,13 @@
|
||||
namespace Data
|
||||
{
|
||||
public class ItemDefine:Define
|
||||
public class ItemDef:Define
|
||||
{
|
||||
public ImageDef texture;
|
||||
public AttributesDef attributes;
|
||||
}
|
||||
|
||||
public class WeaponDef : ItemDef
|
||||
{
|
||||
|
||||
}
|
||||
}
|
@ -8,49 +8,12 @@ namespace Data
|
||||
public class PawnDef : Define
|
||||
{
|
||||
public AttributesDef attributes;
|
||||
public string aiController;
|
||||
public string texturePath = null;
|
||||
public DrawingOrderDef
|
||||
drawingOrder_down,
|
||||
drawingOrder_up,
|
||||
drawingOrder_left,
|
||||
drawingOrder_right;
|
||||
public DrawingOrderDef drawingOrder;
|
||||
|
||||
public BehaviorTreeDef behaviorTree;
|
||||
public string affiliation;
|
||||
|
||||
|
||||
public DrawingOrderDef GetDrawingOrder(Orientation orientation)
|
||||
{
|
||||
// 定义一个临时变量用于存储结果
|
||||
DrawingOrderDef result = null;
|
||||
|
||||
// 根据传入的 Orientation 获取对应的 DrawingOrderDef
|
||||
switch (orientation)
|
||||
{
|
||||
case Orientation.Down:
|
||||
result = drawingOrder_down;
|
||||
break;
|
||||
case Orientation.Up:
|
||||
result = drawingOrder_up;
|
||||
break;
|
||||
case Orientation.Left:
|
||||
result = drawingOrder_left;
|
||||
break;
|
||||
case Orientation.Right:
|
||||
result = drawingOrder_right;
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentException("Invalid orientation value.");
|
||||
}
|
||||
|
||||
// 如果当前方向的结果为空,则尝试用 drawingOrder_down 填充
|
||||
if (result == null) result = drawingOrder_down;
|
||||
|
||||
// 如果 drawingOrder_down 仍然为空,则尝试用其他非空方向填充
|
||||
if (result == null) result = drawingOrder_up ?? drawingOrder_left ?? drawingOrder_right;
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
public class MonsterDef:PawnDef
|
||||
{
|
||||
@ -60,29 +23,38 @@ namespace Data
|
||||
public class BehaviorTreeDef : Define
|
||||
{
|
||||
public BehaviorTreeDef[] childTree;
|
||||
public string className;
|
||||
public string className="Selector";
|
||||
public string condition;
|
||||
|
||||
|
||||
public override bool Init(XElement xmlDef)
|
||||
{
|
||||
base.Init(xmlDef);
|
||||
|
||||
// 从当前节点获取className和condition属性
|
||||
className = xmlDef.Attribute("className")?.Value ?? className;
|
||||
condition = xmlDef.Attribute("condition")?.Value;
|
||||
|
||||
var nodes = xmlDef.Elements("Node");
|
||||
var xElements = nodes as XElement[] ?? nodes.ToArray();
|
||||
if (!xElements.Any())
|
||||
return false;
|
||||
if (!nodes.Any())
|
||||
return true; // 没有子节点也是有效的
|
||||
|
||||
className = xmlDef.Attribute("className")?.Value;
|
||||
List<BehaviorTreeDef> children = new();
|
||||
foreach (var node in xElements)
|
||||
foreach (var node in nodes)
|
||||
{
|
||||
var childNode = new BehaviorTreeDef();
|
||||
childNode.Init(node);
|
||||
if (!childNode.Init(node))
|
||||
return false;
|
||||
children.Add(childNode);
|
||||
}
|
||||
|
||||
childTree = children.ToArray();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public class AffiliationDef : Define
|
||||
{
|
||||
|
||||
}
|
||||
}
|
10
Client/Assets/Scripts/Entity/BuildingBase.cs
Normal file
10
Client/Assets/Scripts/Entity/BuildingBase.cs
Normal file
@ -0,0 +1,10 @@
|
||||
namespace Entity
|
||||
{
|
||||
public class BuildingBase:Entity
|
||||
{
|
||||
public override void TryMove()
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
}
|
3
Client/Assets/Scripts/Entity/BuildingBase.cs.meta
Normal file
3
Client/Assets/Scripts/Entity/BuildingBase.cs.meta
Normal file
@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: eb881a08fe004eb4ab0a6fa9d5d86d33
|
||||
timeCreated: 1753100586
|
@ -10,12 +10,11 @@ namespace Entity
|
||||
public class Character : Entity
|
||||
{
|
||||
public CharacterDef characterDef;
|
||||
public GameObject body;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
aiTree = new RandomWander();
|
||||
runtimeAttributes = new AttributesDef();
|
||||
attributes = new AttributesDef();
|
||||
}
|
||||
|
||||
public void Init()
|
||||
|
@ -1,18 +1,25 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using AI;
|
||||
using Base;
|
||||
using Data;
|
||||
using Prefab;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Serialization;
|
||||
|
||||
namespace Entity
|
||||
{
|
||||
public abstract class Entity:MonoBehaviour,ITick
|
||||
public class Entity:MonoBehaviour,ITick
|
||||
{
|
||||
public SpriteAnimator animatorPrefab;
|
||||
public ImagePrefab imagePrefab;
|
||||
|
||||
public AIBase aiTree;
|
||||
public JobBase currentJob;
|
||||
public AttributesDef runtimeAttributes;
|
||||
public AttributesDef attributes=new();
|
||||
public Vector3 direction;
|
||||
public GameObject body;
|
||||
public string affiliation;
|
||||
|
||||
public bool canSelect = true;
|
||||
public bool IsChase { set; get; } = true;
|
||||
@ -20,23 +27,111 @@ namespace Entity
|
||||
{
|
||||
set
|
||||
{
|
||||
if (!value)
|
||||
if (value)
|
||||
{
|
||||
IsChase = true;
|
||||
currentJob = null;
|
||||
}
|
||||
_isPlayerControlled = value;
|
||||
}
|
||||
get => _isPlayerControlled;
|
||||
}
|
||||
|
||||
|
||||
public bool IsDead => attributes.health <= 0;
|
||||
|
||||
private bool _isPlayerControlled = false;
|
||||
private bool _warning = false;
|
||||
|
||||
private Dictionary<Orientation,List<ITick>> bodyAnimationNode=new();
|
||||
private Dictionary<Orientation, GameObject> bodyNodes = new();
|
||||
|
||||
private const int WarningInterval = 5000;
|
||||
private int _warningTicks = 0;
|
||||
|
||||
private Orientation currentOrientation = Orientation.Down;
|
||||
|
||||
public virtual void Init(PawnDef pawnDef)
|
||||
{
|
||||
attributes = pawnDef.attributes.Clone();
|
||||
aiTree = ConvertToAIBase(pawnDef.behaviorTree);
|
||||
affiliation = pawnDef.affiliation;
|
||||
InitBody(pawnDef.drawingOrder);
|
||||
}
|
||||
|
||||
public virtual void InitBody(DrawingOrderDef drawingOrder)
|
||||
{
|
||||
// 定义方向枚举和对应的 GetDrawingOrder 调用
|
||||
Orientation[] orientations = { Orientation.Down, Orientation.Up, Orientation.Left, Orientation.Right };
|
||||
|
||||
foreach (var orientation in orientations)
|
||||
{
|
||||
currentOrientation = orientation;
|
||||
bodyAnimationNode[orientation] = new();
|
||||
// 获取当前方向的绘图节点
|
||||
var drawNode = drawingOrder.GetDrawingOrder(orientation);
|
||||
|
||||
if (drawNode == null) continue;
|
||||
var directionRoot = new GameObject(orientation.ToString());
|
||||
directionRoot.transform.SetParent(body.transform, false);
|
||||
InitBodyPart(drawNode, directionRoot,drawingOrder.texturePath);
|
||||
bodyNodes[orientation] = directionRoot;
|
||||
}
|
||||
currentOrientation = Orientation.Down;
|
||||
|
||||
foreach (var bodyNode in bodyNodes)
|
||||
{
|
||||
bodyNode.Value.SetActive(false);
|
||||
}
|
||||
SetOrientation(Orientation.Down);
|
||||
}
|
||||
|
||||
// 递归初始化单个绘图节点及其子节点
|
||||
public virtual void InitBodyPart(DrawNodeDef drawNode, GameObject parent,string folderPath)
|
||||
{
|
||||
if(drawNode==null) return;
|
||||
|
||||
GameObject nodeObject;
|
||||
if (drawNode.nodeName == "noName")
|
||||
{
|
||||
nodeObject = new();
|
||||
nodeObject.transform.SetParent(parent.transform);
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (drawNode.drawNodeType)
|
||||
{
|
||||
case DrawNodeType.Image:
|
||||
nodeObject = Instantiate(imagePrefab.gameObject, parent.transform);
|
||||
var texture =
|
||||
Managers.PackagesImageManager.Instance.FindBodyTextures(drawNode.packID, folderPath,
|
||||
$"{drawNode.nodeName}_{currentOrientation}");
|
||||
var image = nodeObject.GetComponent<ImagePrefab>();
|
||||
image.SetSprite(texture[0]);
|
||||
break;
|
||||
|
||||
case DrawNodeType.Animation:
|
||||
nodeObject = Instantiate(animatorPrefab.gameObject, parent.transform);
|
||||
ITick tick = nodeObject.GetComponent<SpriteAnimator>();
|
||||
if (tick != null)
|
||||
bodyAnimationNode[currentOrientation].Add(tick);
|
||||
var textures = Managers.PackagesImageManager.Instance.FindBodyTextures(drawNode.packID,
|
||||
folderPath,
|
||||
$"{drawNode.nodeName}_{currentOrientation}");
|
||||
var animator = nodeObject.GetComponent<SpriteAnimator>();
|
||||
animator.SetSprites(textures);
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException();
|
||||
}
|
||||
}
|
||||
nodeObject.transform.localPosition = drawNode.position;
|
||||
nodeObject.name = drawNode.nodeName;
|
||||
// 递归初始化子节点
|
||||
foreach (var child in drawNode.children)
|
||||
{
|
||||
InitBodyPart(child, nodeObject,folderPath);
|
||||
}
|
||||
}
|
||||
public void Tick()
|
||||
{
|
||||
if (PlayerControlled)
|
||||
if (_isPlayerControlled)
|
||||
{
|
||||
UpdatePlayerControls();
|
||||
}
|
||||
@ -44,26 +139,41 @@ namespace Entity
|
||||
{
|
||||
AutoBehave();
|
||||
}
|
||||
|
||||
if (bodyAnimationNode.TryGetValue(currentOrientation, out var ticks))
|
||||
{
|
||||
foreach (var tick in ticks)
|
||||
{
|
||||
tick.Tick();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public virtual void TryAttck()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public virtual void SetOrientation(Orientation orientation)
|
||||
{
|
||||
bodyNodes[currentOrientation]?.SetActive(false);
|
||||
currentOrientation = orientation;
|
||||
bodyNodes[orientation]?.SetActive(true);
|
||||
}
|
||||
/// <summary>
|
||||
/// 往对应朝向移动moveSpeed*deltaTime的距离
|
||||
/// </summary>
|
||||
public virtual void TryMove()
|
||||
{
|
||||
transform.position+=direction * (runtimeAttributes.moveSpeed * Time.deltaTime * (IsChase ? 1 : 0.5f));
|
||||
transform.position += direction * (attributes.moveSpeed * Time.deltaTime * (IsChase ? 1 : 0.5f));
|
||||
}
|
||||
|
||||
public virtual void OnHit(Entity from)
|
||||
{
|
||||
var hit = from.runtimeAttributes.attack - runtimeAttributes.defense;
|
||||
var hit = from.attributes.attack - attributes.defense;
|
||||
if (hit < 0)
|
||||
hit = from.runtimeAttributes.attack / 100;
|
||||
runtimeAttributes.health -= hit;
|
||||
hit = from.attributes.attack / 100;
|
||||
attributes.health -= hit;
|
||||
|
||||
currentJob.StopJob();
|
||||
}
|
||||
@ -73,25 +183,25 @@ namespace Entity
|
||||
direction = (pos - transform.position).normalized;
|
||||
}
|
||||
|
||||
public virtual void Kill(float delay = 0)
|
||||
public virtual void Kill()
|
||||
{
|
||||
Destroy(gameObject,delay);
|
||||
attributes.health = 0;
|
||||
}
|
||||
|
||||
private void AutoBehave()
|
||||
{
|
||||
if(aiTree == null)
|
||||
return;
|
||||
if (currentJob == null || !currentJob.Running)
|
||||
{
|
||||
currentJob = aiTree.GetJob(this);
|
||||
if (currentJob == null)
|
||||
{
|
||||
if (_warningTicks<=0)
|
||||
if (!_warning)
|
||||
{
|
||||
Debug.LogWarning($"{GetType().Name}类型的{name}没有分配到任何工作,给行为树末尾添加等待行为,避免由于没有工作导致无意义的反复查找工作导致性能问题");
|
||||
_warningTicks += WarningInterval;
|
||||
_warning = true;
|
||||
}
|
||||
|
||||
_warningTicks--;
|
||||
return;
|
||||
}
|
||||
currentJob.StartJob(this);
|
||||
@ -102,42 +212,97 @@ namespace Entity
|
||||
|
||||
private void UpdatePlayerControls()
|
||||
{
|
||||
// 获取当前键盘输入状态
|
||||
var inputDirection = new Vector3();
|
||||
// 检测 Shift 键状态
|
||||
var isHoldingShift = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);
|
||||
IsChase = !isHoldingShift; // 按住 Shift 时 IsChase = false,否则 true
|
||||
// 获取当前键盘输入状态(2D 移动,只使用 X 和 Y 轴)
|
||||
var inputDirection = Vector2.zero;
|
||||
|
||||
// 检测 WASD 输入
|
||||
// 检测 WASD 或方向键输入
|
||||
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
|
||||
{
|
||||
inputDirection += Vector3.forward; // 向前移动
|
||||
inputDirection += Vector2.up; // 向上移动(Y 轴正方向)
|
||||
}
|
||||
if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
|
||||
{
|
||||
inputDirection += Vector3.back; // 向后移动
|
||||
inputDirection += Vector2.down; // 向下移动(Y 轴负方向)
|
||||
}
|
||||
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
|
||||
{
|
||||
inputDirection += Vector3.left; // 向左移动
|
||||
inputDirection += Vector2.left; // 向左移动(X 轴负方向)
|
||||
}
|
||||
if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
|
||||
{
|
||||
inputDirection += Vector3.right; // 向右移动
|
||||
inputDirection += Vector2.right; // 向右移动(X 轴正方向)
|
||||
}
|
||||
|
||||
// 如果有输入方向,则设置目标位置并尝试移动
|
||||
if (inputDirection != Vector3.zero)
|
||||
if (inputDirection == Vector2.zero) return;
|
||||
// 归一化方向向量,确保对角线移动速度一致
|
||||
inputDirection = inputDirection.normalized;
|
||||
|
||||
// 设置目标位置(2D 移动,Z 轴保持不变)
|
||||
var targetPosition = transform.position + new Vector3(inputDirection.x, inputDirection.y, 0);
|
||||
|
||||
// 调用 SetTarget 方法设置目标位置
|
||||
SetTarget(targetPosition);
|
||||
|
||||
// 调用 TryMove 方法处理实际移动逻辑
|
||||
TryMove();
|
||||
}
|
||||
public static AIBase ConvertToAIBase(BehaviorTreeDef behaviorTreeDef)
|
||||
{
|
||||
if (behaviorTreeDef == null)
|
||||
return null;
|
||||
var aiBase = CreateAIBaseInstance(behaviorTreeDef.className);
|
||||
if (behaviorTreeDef.childTree != null)
|
||||
{
|
||||
// 归一化方向向量,确保对角线移动速度一致
|
||||
inputDirection = inputDirection.normalized;
|
||||
|
||||
// 设置目标位置(假设当前位置为 transform.position)
|
||||
Vector3 targetPosition = transform.position + inputDirection;
|
||||
|
||||
// 调用 SetTarget 方法设置目标位置
|
||||
SetTarget(targetPosition);
|
||||
|
||||
// 调用 TryMove 方法处理实际移动逻辑
|
||||
TryMove();
|
||||
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 不能为空");
|
||||
if (className.Equals("AIBase", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return (AIBase)Activator.CreateInstance(typeof(AIBase));
|
||||
}
|
||||
// 定义可能的命名空间列表
|
||||
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 的子类");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,13 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Events;
|
||||
|
||||
namespace Entity
|
||||
{
|
||||
public class Outline:MonoBehaviour
|
||||
public class Outline : MonoBehaviour
|
||||
{
|
||||
public GameObject body;
|
||||
public SpriteRenderer outlineRenderer;
|
||||
public CapsuleCollider2D outlineCollider;
|
||||
|
||||
public Entity entity;
|
||||
|
||||
private bool _select = false;
|
||||
|
||||
public void Init()
|
||||
{
|
||||
var size = GetSize();
|
||||
@ -15,15 +22,17 @@ namespace Entity
|
||||
outlineCollider.direction = size.x > size.y ? CapsuleDirection2D.Horizontal : CapsuleDirection2D.Vertical;
|
||||
outlineCollider.size = size;
|
||||
}
|
||||
|
||||
public void Show()
|
||||
{
|
||||
outlineRenderer.gameObject.SetActive(true);
|
||||
outlineRenderer.enabled = true;
|
||||
}
|
||||
|
||||
public void Hide()
|
||||
{
|
||||
outlineRenderer.gameObject.SetActive(false);
|
||||
outlineRenderer.enabled = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定对象及其所有子对象组成的图像的大小。
|
||||
/// </summary>
|
||||
@ -37,15 +46,52 @@ namespace Entity
|
||||
|
||||
if (renderers.Length == 0)
|
||||
{
|
||||
return new(-1,-1);
|
||||
return new(-1, -1);
|
||||
}
|
||||
|
||||
var totalBounds = renderers[0].bounds;
|
||||
for (var i = 1; i < renderers.Length; i++)
|
||||
{
|
||||
totalBounds.Encapsulate(renderers[i].bounds);
|
||||
}
|
||||
|
||||
var size = totalBounds.size;
|
||||
return size;
|
||||
}
|
||||
|
||||
private void OnMouseEnter()
|
||||
{
|
||||
Show();
|
||||
_select = true;
|
||||
}
|
||||
|
||||
private void OnMouseExit()
|
||||
{
|
||||
Hide();
|
||||
_select = false;
|
||||
}
|
||||
|
||||
private void OnMouseOver()
|
||||
{
|
||||
// 检测是否按下的是鼠标右键
|
||||
if (Input.GetMouseButtonDown(1)) // 鼠标右键对应的是按钮索引 1
|
||||
{
|
||||
var rightMenu = Prefab.RightMenuPrefab.Instance;
|
||||
rightMenu.Init(GetMenu());
|
||||
rightMenu.transform.position=Input.mousePosition;
|
||||
rightMenu.Show();
|
||||
}
|
||||
}
|
||||
|
||||
private List<(string name, UnityAction callback)> GetMenu()
|
||||
{
|
||||
var result = new List<(string name, UnityAction callback)>();
|
||||
if(entity.PlayerControlled)
|
||||
result.Add(("结束操控",()=>entity.PlayerControlled=false));
|
||||
else
|
||||
result.Add(("手动操控",()=>entity.PlayerControlled=true));
|
||||
result.Add(("杀死",()=>entity.Kill()));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
@ -14,9 +15,11 @@ namespace Managers
|
||||
public class DefineManager : Singleton<DefineManager>
|
||||
{
|
||||
private static readonly string[] dataSetFilePath = { "Data", "Mods" };
|
||||
|
||||
//类别,定义名,定义
|
||||
public Dictionary<string, Dictionary<string, Define>> defines = new();
|
||||
//包id,包
|
||||
public Dictionary<string, DefinePack> packs = new();
|
||||
//类别,定义
|
||||
public Dictionary<string, List<Define>> anonymousDefines = new();
|
||||
/// <summary>
|
||||
/// 初始化定义管理器,加载所有定义包并构建定义字典。
|
||||
@ -44,15 +47,18 @@ namespace Managers
|
||||
|
||||
|
||||
Dictionary<Type, FieldInfo[]> fieldCache = new();
|
||||
// 需要链接的定义、需要链接的字段、链接信息
|
||||
List<Tuple<Define, FieldInfo, Define>> defineCache = new();
|
||||
HashSet<Define> processedDefines = new(); // 用于跟踪已处理的 Define 对象
|
||||
|
||||
string currentPackID = string.Empty;
|
||||
|
||||
void ProcessDefine(Define def, Define parentDef, FieldInfo parentField)
|
||||
|
||||
void ProcessDefine(Define def)
|
||||
{
|
||||
if (def == null || def.isReferene || processedDefines.Contains(def))
|
||||
if (def == null || def.isReferene)
|
||||
return;
|
||||
|
||||
processedDefines.Add(def);
|
||||
def.packID = currentPackID;
|
||||
|
||||
// 如果字段信息已经缓存,则直接使用缓存
|
||||
if (!fieldCache.TryGetValue(def.GetType(), out var defineFields))
|
||||
@ -60,57 +66,123 @@ namespace Managers
|
||||
// 获取所有字段类型为 Define 或其派生类型的字段
|
||||
defineFields = def.GetType()
|
||||
.GetFields(BindingFlags.Public | BindingFlags.Instance)
|
||||
.Where(field => typeof(Define).IsAssignableFrom(field.FieldType))
|
||||
.ToArray();
|
||||
.ToArray(); // 不再过滤,先获取所有字段
|
||||
|
||||
// 缓存字段信息
|
||||
fieldCache[def.GetType()] = defineFields;
|
||||
}
|
||||
|
||||
foreach (var defineField in defineFields)
|
||||
{
|
||||
var defRef = (Define)defineField.GetValue(def);
|
||||
if (defRef == null)
|
||||
continue;
|
||||
if (defRef.isReferene)
|
||||
var fieldType = defineField.FieldType;
|
||||
|
||||
// 处理单个 Define 类型的字段
|
||||
if (typeof(Define).IsAssignableFrom(fieldType))
|
||||
{
|
||||
defineCache.Add(new Tuple<Define, FieldInfo, Define>(parentDef, parentField, defRef));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (string.IsNullOrEmpty(defRef.defName))
|
||||
var defRef = (Define)defineField.GetValue(def);
|
||||
if (defRef == null)
|
||||
continue;
|
||||
|
||||
if (defRef.isReferene)
|
||||
{
|
||||
var typeName = defRef.GetType().Name;
|
||||
if (!anonymousDefines.ContainsKey(typeName))
|
||||
anonymousDefines.Add(typeName, new List<Define>());
|
||||
anonymousDefines[typeName].Add(defRef);
|
||||
defineCache.Add(new Tuple<Define, FieldInfo, Define>(def, defineField, defRef));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (string.IsNullOrEmpty(defRef.defName))
|
||||
{
|
||||
var typeName = defRef.GetType().Name;
|
||||
if (!anonymousDefines.ContainsKey(typeName))
|
||||
anonymousDefines.Add(typeName, new List<Define>());
|
||||
anonymousDefines[typeName].Add(defRef);
|
||||
}
|
||||
ProcessDefine(defRef);
|
||||
}
|
||||
}
|
||||
// 处理集合类型字段
|
||||
else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(List<>))
|
||||
{
|
||||
var elementType = fieldType.GenericTypeArguments[0];
|
||||
if (typeof(Define).IsAssignableFrom(elementType))
|
||||
{
|
||||
var list = (IList)defineField.GetValue(def);
|
||||
if (list != null)
|
||||
{
|
||||
foreach (var item in list)
|
||||
{
|
||||
if (item is Define defItem && !defItem.isReferene)
|
||||
{
|
||||
ProcessDefine(defItem);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 处理数组类型字段
|
||||
else if (fieldType.IsArray)
|
||||
{
|
||||
var elementType = fieldType.GetElementType();
|
||||
if (typeof(Define).IsAssignableFrom(elementType))
|
||||
{
|
||||
var array = (Array)defineField.GetValue(def);
|
||||
if (array != null)
|
||||
{
|
||||
foreach (var item in array)
|
||||
{
|
||||
if (item is Define defItem && !defItem.isReferene)
|
||||
{
|
||||
ProcessDefine(defItem);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ProcessDefine(defRef, def, defineField);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var pack in packs)
|
||||
{
|
||||
foreach (var define in pack.Value.defines)
|
||||
currentPackID = pack.Value.packID;
|
||||
foreach (var (typeName, defList) in pack.Value.defines)
|
||||
{
|
||||
var typeName = define.Key;
|
||||
var defList = define.Value;
|
||||
|
||||
if (!defines.ContainsKey(typeName))
|
||||
defines[typeName] = new Dictionary<string, Define>();
|
||||
|
||||
|
||||
foreach (var def in defList)
|
||||
{
|
||||
defines[typeName][def.defName] = def;
|
||||
|
||||
// 处理顶层 Define
|
||||
ProcessDefine(def, null, null);
|
||||
ProcessDefine(def);
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (var defRef in defineCache)
|
||||
{
|
||||
defRef.Item2.SetValue(defRef.Item1, FindDefine(defRef.Item3.description, defRef.Item3.defName));
|
||||
if (defRef.Item1 == null)
|
||||
{
|
||||
Debug.LogError("defRef.Item1 为 null!");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (defRef.Item2 == null)
|
||||
{
|
||||
Debug.LogError("defRef.Item2 为 null!");
|
||||
continue;
|
||||
}
|
||||
|
||||
var value = FindDefine(defRef.Item3.description, defRef.Item3.defName);
|
||||
if (value == null)
|
||||
{
|
||||
Debug.LogError($"FindDefine 返回 null: description={defRef.Item3.description}, defName={defRef.Item3.defName}");
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
defRef.Item2.SetValue(defRef.Item1, value);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogError($"SetValue 出错: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -138,7 +210,23 @@ namespace Managers
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用模板查找并返回指定类型的 Define 对象。
|
||||
/// </summary>
|
||||
/// <typeparam name="T">目标类型</typeparam>
|
||||
/// <param name="defineName">定义名</param>
|
||||
/// <returns>如果找到,返回转换为目标类型的 Define 对象;否则返回 null。</returns>
|
||||
public T FindDefine<T>(string defineName) where T : Define
|
||||
{
|
||||
foreach (var typeDict in defines.Values)
|
||||
{
|
||||
if (typeDict.TryGetValue(defineName, out var define) && define is T result)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public DefinePack GetDefinePackage(Define define)
|
||||
{
|
||||
if (define == null || define.packID == null)
|
||||
@ -340,4 +428,5 @@ namespace Managers
|
||||
return result.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
133
Client/Assets/Scripts/Managers/EntityManage.cs
Normal file
133
Client/Assets/Scripts/Managers/EntityManage.cs
Normal file
@ -0,0 +1,133 @@
|
||||
using System;
|
||||
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 EntityPrefab defaultEntityPrefab;
|
||||
|
||||
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.");
|
||||
GenerateDefaultEntity(pos);
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查pawnDef是否为空
|
||||
if (pawnDef == null)
|
||||
{
|
||||
Debug.LogError("Error: PawnDef is null. Cannot generate entity without a valid PawnDef.");
|
||||
GenerateDefaultEntity(pos);
|
||||
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}");
|
||||
GenerateDefaultEntity(pos);
|
||||
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}\nStack Trace: {ex.StackTrace}");
|
||||
GenerateDefaultEntity(pos);
|
||||
}
|
||||
}
|
||||
|
||||
public void GenerateDefaultEntity(Vector3 pos)
|
||||
{
|
||||
var entity = Instantiate(entityPrefab.gameObject, pos, Quaternion.identity, entityLevel.transform);
|
||||
var entityComponent = entity.GetComponent<EntityPrefab>();
|
||||
const string factionKey = "default";
|
||||
if (!factionEntities.ContainsKey(factionKey))
|
||||
{
|
||||
factionEntities[factionKey] = new List<EntityPrefab>();
|
||||
}
|
||||
factionEntities[factionKey].Add(entityComponent);
|
||||
}
|
||||
protected override void OnStart()
|
||||
{
|
||||
factionEntities.Clear();
|
||||
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
var pre = Resources.Load<GameObject>("Default/DefaultEntity");
|
||||
defaultEntityPrefab = pre.GetComponent<EntityPrefab>();
|
||||
|
||||
}
|
||||
}
|
||||
}
|
3
Client/Assets/Scripts/Managers/EntityManage.cs.meta
Normal file
3
Client/Assets/Scripts/Managers/EntityManage.cs.meta
Normal file
@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: aa378b7511b04429b8b6b0efbcce825a
|
||||
timeCreated: 1753149728
|
@ -1,22 +0,0 @@
|
||||
using Prefab;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Managers
|
||||
{
|
||||
public class Generator:MonoBehaviour
|
||||
{
|
||||
public GameObject entityLevel;
|
||||
public EntityPrefab entityPrefab;
|
||||
|
||||
public void GenerateEntity(Data.PawnDef pawnDef, Vector3 pos)
|
||||
{
|
||||
if (entityPrefab == null || pawnDef == null)
|
||||
return;
|
||||
|
||||
GameObject entity = Instantiate(entityPrefab.gameObject, pos, Quaternion.identity, entityLevel.transform);
|
||||
// entity.name = pawnDef.name;
|
||||
var entityComponent = entity.GetComponent<EntityPrefab>();
|
||||
entityComponent?.Init(pawnDef);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,3 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d78f1b5a44344a4a987e308d3b9478cc
|
||||
timeCreated: 1752937967
|
@ -1,68 +1,151 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Data;
|
||||
using NUnit.Framework;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Managers
|
||||
{
|
||||
public class PackagesImageManager : Utils.Singleton<PackagesImageManager>
|
||||
{
|
||||
public Dictionary<string, Texture2D> packagesImages = new();
|
||||
public Dictionary<string, Sprite> sprites = new();
|
||||
public Sprite defaultSprite;
|
||||
//包名,图片名
|
||||
public Dictionary<string, Dictionary<string, Texture2D>> packagesImages = new();
|
||||
//包名,图片名
|
||||
public Dictionary<string, Dictionary<string, Sprite>> sprites = new();
|
||||
//包名,文件路径,身体部件名
|
||||
public Dictionary<string, Dictionary<string, Dictionary<string, Sprite>>> bodyTexture = new();
|
||||
|
||||
public void Init()
|
||||
{
|
||||
if (packagesImages.Count > 0)
|
||||
return;
|
||||
defaultSprite = Resources.Load<Sprite>("Default/DefaultImage");
|
||||
InitImageDef();
|
||||
InitDrawOrder();
|
||||
packagesImages = null;
|
||||
}
|
||||
|
||||
public void InitImageDef()
|
||||
{
|
||||
var imageDef = Managers.DefineManager.Instance.QueryDefinesByType<ImageDef>();
|
||||
foreach (var ima in imageDef)
|
||||
{
|
||||
if (ima.path == null)
|
||||
if (ima.path == null || ima.packID == null)
|
||||
continue;
|
||||
var pack = Managers.DefineManager.Instance.GetDefinePackage(ima);
|
||||
var path = Path.Combine(pack.packRootPath, ima.path);
|
||||
var texture = Configs.ConfigProcessor.LoadTextureByIO(path);
|
||||
if (texture == null)
|
||||
continue;
|
||||
packagesImages.Add(ima.name, texture);
|
||||
SplitTextureIntoSprites(ima.name, texture, ima.hCount, ima.wCount, ima.pixelsPerUnit);
|
||||
continue;
|
||||
|
||||
var packId = ima.packID;
|
||||
|
||||
if (!packagesImages.ContainsKey(packId))
|
||||
packagesImages[packId] = new Dictionary<string, Texture2D>();
|
||||
packagesImages[packId].Add(ima.name, texture);
|
||||
|
||||
SplitTextureIntoSprites(packId, ima.name, texture, ima.hCount, ima.wCount, ima.pixelsPerUnit);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void InitDrawOrder()
|
||||
{
|
||||
var drawOrderDef = Managers.DefineManager.Instance.QueryDefinesByType<DrawingOrderDef>();
|
||||
if (drawOrderDef == null || drawOrderDef.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
Dictionary<string, string> packRootSite = new();
|
||||
foreach (var drawOrder in drawOrderDef)
|
||||
{
|
||||
if (string.IsNullOrEmpty(drawOrder.texturePath) || string.IsNullOrEmpty(drawOrder.packID))
|
||||
continue;
|
||||
if (!packRootSite.ContainsKey(drawOrder.packID))
|
||||
packRootSite[drawOrder.packID] = Managers.DefineManager.Instance.GetPackagePath(drawOrder.packID);
|
||||
var rootPath= packRootSite[drawOrder.packID];
|
||||
var folderPath=Path.Combine(rootPath, drawOrder.texturePath);
|
||||
var imagePath = Configs.ConfigProcessor.GetFilesByExtensions(folderPath,
|
||||
new[]
|
||||
{
|
||||
"jpg", "jpeg", "png", "tga", "tif", "tiff", "psd", "bmp"
|
||||
});
|
||||
foreach (var path in imagePath)
|
||||
{
|
||||
var image=Configs.ConfigProcessor.LoadTextureByIO(path);
|
||||
if (image == null)
|
||||
continue;
|
||||
var spr=Sprite.Create(
|
||||
image,
|
||||
new Rect(0, 0, image.width, image.height),
|
||||
new Vector2(0.5f, 0.5f) // 中心点
|
||||
);
|
||||
var name=Path.GetFileNameWithoutExtension(path);
|
||||
InsertBodyTexture(drawOrder.packID, drawOrder.texturePath, name, spr);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SplitTextureIntoSprites(string name, Texture2D texture, int rows, int cols, int pixelsPerUnit)
|
||||
private void SplitTextureIntoSprites(
|
||||
string packId,
|
||||
string baseName,
|
||||
Texture2D texture,
|
||||
int rows,
|
||||
int cols,
|
||||
int pixelsPerUnit)
|
||||
{
|
||||
if (texture == null || rows <= 0 || cols <= 0)
|
||||
if (texture == null)
|
||||
{
|
||||
Debug.LogError("Invalid parameters for splitting texture.");
|
||||
Debug.LogError("Texture is null.");
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果行数或列数小于1,则设为1(不分割)
|
||||
rows = Mathf.Max(1, rows);
|
||||
cols = Mathf.Max(1, cols);
|
||||
|
||||
var textureWidth = texture.width;
|
||||
var textureHeight = texture.height;
|
||||
|
||||
// 如果不分割(rows和cols都为1),直接创建单个Sprite
|
||||
if (rows == 1 && cols == 1)
|
||||
{
|
||||
if (!sprites.ContainsKey(packId))
|
||||
sprites[packId] = new Dictionary<string, Sprite>();
|
||||
|
||||
var spriteRect = new Rect(0, 0, textureWidth, textureHeight);
|
||||
var sprite = Sprite.Create(texture, spriteRect, new Vector2(0.5f, 0.5f), pixelsPerUnit);
|
||||
sprites[packId][baseName] = sprite;
|
||||
return;
|
||||
}
|
||||
|
||||
var tileWidth = textureWidth / cols;
|
||||
var tileHeight = textureHeight / rows;
|
||||
|
||||
// 确保纹理可以被整除
|
||||
if (tileWidth * cols != textureWidth || tileHeight * rows != textureHeight)
|
||||
{
|
||||
Debug.LogError("Texture dimensions are not divisible by the specified rows and columns.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!sprites.ContainsKey(packId))
|
||||
sprites[packId] = new Dictionary<string, Sprite>();
|
||||
|
||||
// 遍历每一行和每一列
|
||||
for (var row = 0; row < rows; row++)
|
||||
{
|
||||
for (var col = 0; col < cols; col++)
|
||||
{
|
||||
// 计算当前小块的矩形区域
|
||||
var spriteRect = new Rect(col * tileWidth, row * tileHeight, tileWidth, tileHeight);
|
||||
|
||||
// 创建Sprite
|
||||
var sprite = Sprite.Create(texture, (Rect)spriteRect, new Vector2(0.5f, 0.5f), pixelsPerUnit);
|
||||
|
||||
Rect spriteRect = new(col * tileWidth, row * tileHeight, tileWidth, tileHeight);
|
||||
var sprite = Sprite.Create(texture, spriteRect, new Vector2(0.5f, 0.5f), pixelsPerUnit);
|
||||
|
||||
var index = (rows - row - 1) * cols + col;
|
||||
sprites[name + $"_{index}"] = sprite;
|
||||
var spriteName = $"{baseName}_{index}";
|
||||
|
||||
sprites[packId][spriteName] = sprite;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -70,18 +153,124 @@ namespace Managers
|
||||
public void Reload()
|
||||
{
|
||||
packagesImages.Clear();
|
||||
sprites.Clear();
|
||||
Init();
|
||||
}
|
||||
|
||||
public Sprite GetSprite(string name)
|
||||
|
||||
public Sprite GetSprite(string packID, string name)
|
||||
{
|
||||
return sprites.GetValueOrDefault(name, null);
|
||||
if (string.IsNullOrEmpty(packID))
|
||||
{
|
||||
foreach (var kvp in sprites)
|
||||
{
|
||||
if (kvp.Value.TryGetValue(name, out var sprite))
|
||||
return sprite;
|
||||
}
|
||||
}
|
||||
else if (sprites.TryGetValue(packID, out var dict))
|
||||
{
|
||||
if (dict.TryGetValue(name, out var sprite))
|
||||
return sprite;
|
||||
}
|
||||
|
||||
return defaultSprite;
|
||||
}
|
||||
|
||||
public Sprite GetSprite(string name, int index)
|
||||
public Sprite GetSprite(string packID, string name, int index)
|
||||
{
|
||||
name += $"_{index}";
|
||||
return GetSprite(name);
|
||||
var fullName = $"{name}_{index}";
|
||||
return GetSprite(packID, fullName);
|
||||
}
|
||||
/// <summary>
|
||||
/// 向 bodyTexture 插入一张 Sprite。
|
||||
/// 如果包名、路径或部件名原本不存在,会自动建立对应的 Dictionary。
|
||||
/// </summary>
|
||||
/// <param name="packageName">包名</param>
|
||||
/// <param name="filePath">文件路径</param>
|
||||
/// <param name="bodyPartName">身体部件名</param>
|
||||
/// <param name="sprite">要插入的 Sprite</param>
|
||||
public void InsertBodyTexture(string packageName,
|
||||
string filePath,
|
||||
string bodyPartName,
|
||||
Sprite sprite)
|
||||
{
|
||||
if (sprite == null)
|
||||
{
|
||||
Debug.LogWarning("InsertBodyTexture: sprite 为 null,已忽略。");
|
||||
return;
|
||||
}
|
||||
|
||||
// 1) 处理包名层级
|
||||
if (!bodyTexture.TryGetValue(packageName, out var pathDict))
|
||||
{
|
||||
pathDict = new Dictionary<string, Dictionary<string, Sprite>>();
|
||||
bodyTexture[packageName] = pathDict;
|
||||
}
|
||||
|
||||
// 2) 处理文件路径层级
|
||||
if (!pathDict.TryGetValue(filePath, out var partDict))
|
||||
{
|
||||
partDict = new Dictionary<string, Sprite>();
|
||||
pathDict[filePath] = partDict;
|
||||
}
|
||||
|
||||
// 3) 插入或覆盖部件名
|
||||
partDict[bodyPartName] = sprite;
|
||||
}
|
||||
/// <summary>
|
||||
/// 查找身体部件的所有Sprite变体(支持带编号的图片)
|
||||
/// </summary>
|
||||
/// <param name="packageName">包名</param>
|
||||
/// <param name="filePath">文件路径</param>
|
||||
/// <param name="bodyPartName">身体部件名</param>
|
||||
/// <returns>按编号排序的Sprite数组,未找到时返回空数组</returns>
|
||||
public Sprite[] FindBodyTextures(string packageName, string filePath, string bodyPartName)
|
||||
{
|
||||
// 检查包名是否存在
|
||||
if (!bodyTexture.TryGetValue(packageName, out var packageDict))
|
||||
{
|
||||
Debug.LogWarning($"Package '{packageName}' not found.");
|
||||
return Array.Empty<Sprite>();
|
||||
}
|
||||
|
||||
// 检查文件路径是否存在
|
||||
if (!packageDict.TryGetValue(filePath, out var pathDict))
|
||||
{
|
||||
Debug.LogWarning($"File path '{filePath}' not found in package '{packageName}'.");
|
||||
return Array.Empty<Sprite>();
|
||||
}
|
||||
|
||||
// 收集所有匹配的Sprite
|
||||
var sprites = new List<(int order, Sprite sprite)>();
|
||||
|
||||
// 查找完全匹配的项(无编号)
|
||||
if (pathDict.TryGetValue(bodyPartName, out var baseSprite))
|
||||
{
|
||||
sprites.Add((0, baseSprite));
|
||||
}
|
||||
|
||||
// 查找带编号的变体
|
||||
var prefix = bodyPartName + "_";
|
||||
foreach (var (key, value) in pathDict)
|
||||
{
|
||||
// 检查是否以部件名+下划线开头
|
||||
if (key.StartsWith(prefix) && key.Length > prefix.Length)
|
||||
{
|
||||
var suffix = key.Substring(prefix.Length);
|
||||
|
||||
// 尝试解析编号
|
||||
if (int.TryParse(suffix, out var number))
|
||||
{
|
||||
sprites.Add((number, Value: value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 按编号排序(无编号视为0)
|
||||
return sprites
|
||||
.OrderBy(x => x.order)
|
||||
.Select(x => x.sprite)
|
||||
.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
@ -142,7 +142,7 @@ namespace Map
|
||||
continue;
|
||||
}
|
||||
|
||||
var sprite = imagePack.GetSprite(val);
|
||||
var sprite = imagePack.GetSprite(mappingTableDef.packID,val);
|
||||
if (sprite == null)
|
||||
{
|
||||
var packName = Managers.DefineManager.Instance.GetDefinePackageName(mappingTableDef);
|
||||
|
@ -16,63 +16,13 @@ namespace Prefab
|
||||
|
||||
public void Init(Data.PawnDef pawnDef)
|
||||
{
|
||||
entity.runtimeAttributes = pawnDef.attributes.Clone();
|
||||
entity.aiTree = ConvertToAIBase(pawnDef.behaviorTree);
|
||||
entity.Init(pawnDef);
|
||||
|
||||
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 的子类");
|
||||
}
|
||||
}
|
||||
}
|
44
Client/Assets/Scripts/Prefab/ImagePrefab.cs
Normal file
44
Client/Assets/Scripts/Prefab/ImagePrefab.cs
Normal file
@ -0,0 +1,44 @@
|
||||
using Base;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Prefab
|
||||
{
|
||||
|
||||
[RequireComponent(typeof(SpriteRenderer))]
|
||||
public class ImagePrefab : MonoBehaviour
|
||||
{
|
||||
public Sprite defaultSprite;
|
||||
|
||||
private SpriteRenderer spriteRenderer;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
spriteRenderer = GetComponent<SpriteRenderer>();
|
||||
if (spriteRenderer == null)
|
||||
{
|
||||
Debug.LogError("SpriteRenderer组件未找到,请确保预制体包含该组件!");
|
||||
return;
|
||||
}
|
||||
if (defaultSprite != null)
|
||||
{
|
||||
spriteRenderer.sprite = defaultSprite;
|
||||
}
|
||||
}
|
||||
|
||||
public void SetSprite(Sprite newSprite)
|
||||
{
|
||||
if (spriteRenderer != null && newSprite != null)
|
||||
{
|
||||
spriteRenderer.sprite = newSprite;
|
||||
}
|
||||
}
|
||||
|
||||
public void SetColor(Color newColor)
|
||||
{
|
||||
if (spriteRenderer != null)
|
||||
{
|
||||
spriteRenderer.color = newColor;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
3
Client/Assets/Scripts/Prefab/ImagePrefab.cs.meta
Normal file
3
Client/Assets/Scripts/Prefab/ImagePrefab.cs.meta
Normal file
@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0c360a9f1baf4eaf9afa85617c395b0d
|
||||
timeCreated: 1753331527
|
89
Client/Assets/Scripts/Prefab/RightMenuPrefab.cs
Normal file
89
Client/Assets/Scripts/Prefab/RightMenuPrefab.cs
Normal file
@ -0,0 +1,89 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Events;
|
||||
using UnityEngine.EventSystems;
|
||||
|
||||
namespace Prefab
|
||||
{
|
||||
public class RightMenuPrefab: Utils.MonoSingleton<RightMenuPrefab>,IPointerExitHandler
|
||||
{
|
||||
public GameObject menu;
|
||||
public ButtonPrefab buttonPrefab;
|
||||
|
||||
public void Show()
|
||||
{
|
||||
gameObject.SetActive(true);
|
||||
}
|
||||
|
||||
public void Hide()
|
||||
{
|
||||
gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
public void Init(List<(string name, UnityAction callback)> buttons)
|
||||
{
|
||||
if (menu == null || buttonPrefab == null)
|
||||
{
|
||||
Debug.LogError("Menu or ButtonPrefab is not assigned!");
|
||||
return;
|
||||
}
|
||||
|
||||
ClearMenu();
|
||||
foreach (var (label, callback) in buttons)
|
||||
{
|
||||
// 实例化按钮预制体
|
||||
var instantiatedButton = Instantiate(buttonPrefab.gameObject, menu.transform);
|
||||
var buttonInstance = instantiatedButton.GetComponent<ButtonPrefab>();
|
||||
|
||||
if (buttonInstance != null)
|
||||
{
|
||||
// 设置按钮文本
|
||||
buttonInstance.Label = label;
|
||||
|
||||
// 创建一个新的回调函数,包含原始回调和隐藏菜单的操作
|
||||
UnityAction wrappedCallback = () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
// 执行原始回调
|
||||
callback?.Invoke();
|
||||
}
|
||||
catch (System.Exception e)
|
||||
{
|
||||
Debug.LogError($"Error executing callback for button '{label}': {e.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
// 隐藏菜单
|
||||
Hide();
|
||||
}
|
||||
};
|
||||
|
||||
// 添加包装后的回调
|
||||
buttonInstance.AddListener(wrappedCallback);
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError("Failed to get ButtonPrefab component from instantiated object!");
|
||||
}
|
||||
}
|
||||
}
|
||||
public void ClearMenu()
|
||||
{
|
||||
// 遍历菜单下的所有子对象并销毁它们
|
||||
foreach (Transform child in menu.transform)
|
||||
{
|
||||
Destroy(child.gameObject);
|
||||
}
|
||||
}
|
||||
protected override void OnStart()
|
||||
{
|
||||
Hide();
|
||||
}
|
||||
|
||||
public void OnPointerExit(PointerEventData eventData)
|
||||
{
|
||||
Hide();
|
||||
}
|
||||
}
|
||||
}
|
3
Client/Assets/Scripts/Prefab/RightMenuPrefab.cs.meta
Normal file
3
Client/Assets/Scripts/Prefab/RightMenuPrefab.cs.meta
Normal file
@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e45cfe2f36eb4f589b6d8f331567974d
|
||||
timeCreated: 1753196238
|
90
Client/Assets/Scripts/Prefab/SpriteAnimator.cs
Normal file
90
Client/Assets/Scripts/Prefab/SpriteAnimator.cs
Normal file
@ -0,0 +1,90 @@
|
||||
using Base;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Prefab
|
||||
{
|
||||
[RequireComponent(typeof(SpriteRenderer))]
|
||||
public class SpriteAnimator : MonoBehaviour, ITick
|
||||
{
|
||||
// 公开字段(可在编辑器中设置)
|
||||
[SerializeField] private Sprite[] _sprites; // 动画精灵序列
|
||||
[SerializeField] private float _fps = 2; // 每秒帧数
|
||||
[SerializeField] private Sprite _staticSprite; // 暂停时的静态精灵
|
||||
|
||||
private SpriteRenderer _renderer; // 渲染器组件
|
||||
private bool _isPaused; // 暂停状态
|
||||
private float _frameTimer; // 帧计时器
|
||||
private int _currentFrameIndex; // 当前帧索引
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
_renderer = GetComponent<SpriteRenderer>();
|
||||
ValidateStartFrame();
|
||||
}
|
||||
|
||||
// ITick接口实现
|
||||
public void Tick()
|
||||
{
|
||||
var deltaTime=Time.deltaTime;
|
||||
if (_isPaused)
|
||||
{
|
||||
HandlePausedState();
|
||||
return;
|
||||
}
|
||||
|
||||
PlayAnimation(deltaTime);
|
||||
}
|
||||
|
||||
private void ValidateStartFrame()
|
||||
{
|
||||
// 确保有精灵时可显示有效帧
|
||||
if (_sprites != null && _sprites.Length > 0)
|
||||
{
|
||||
_currentFrameIndex = Mathf.Clamp(_currentFrameIndex, 0, _sprites.Length - 1);
|
||||
_renderer.sprite = _sprites[_currentFrameIndex];
|
||||
}
|
||||
else
|
||||
{
|
||||
_renderer.sprite = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void HandlePausedState()
|
||||
{
|
||||
// 优先使用静态精灵,否则保持当前帧
|
||||
if (_staticSprite)
|
||||
{
|
||||
_renderer.sprite = _staticSprite;
|
||||
}
|
||||
}
|
||||
|
||||
private void PlayAnimation(float deltaTime)
|
||||
{
|
||||
if (_sprites == null || _sprites.Length == 0) return;
|
||||
|
||||
// 更新帧计时器
|
||||
_frameTimer += deltaTime;
|
||||
float frameDuration = 1f / _fps;
|
||||
|
||||
// 检查帧切换条件
|
||||
while (_frameTimer >= frameDuration)
|
||||
{
|
||||
_frameTimer -= frameDuration;
|
||||
NextFrame();
|
||||
}
|
||||
}
|
||||
|
||||
private void NextFrame()
|
||||
{
|
||||
// 循环播放动画
|
||||
_currentFrameIndex = (_currentFrameIndex + 1) % _sprites.Length;
|
||||
_renderer.sprite = _sprites[_currentFrameIndex];
|
||||
}
|
||||
|
||||
// 外部控制方法
|
||||
public void SetPaused(bool paused) => _isPaused = paused;
|
||||
public void SetSprites(Sprite[] newSprites) => _sprites = newSprites;
|
||||
public void SetFPS(float newFPS) => _fps = Mathf.Max(0.1f, newFPS);
|
||||
public void SetStaticSprite(Sprite sprite) => _staticSprite = sprite;
|
||||
}
|
||||
}
|
3
Client/Assets/Scripts/Prefab/SpriteAnimator.cs.meta
Normal file
3
Client/Assets/Scripts/Prefab/SpriteAnimator.cs.meta
Normal file
@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 713a1742950a45d8b4be258a82321e45
|
||||
timeCreated: 1753282330
|
@ -1,31 +0,0 @@
|
||||
using Base;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Test
|
||||
{
|
||||
public class ClockTest : MonoBehaviour
|
||||
{
|
||||
//private static float timer = 0;
|
||||
|
||||
// Start is called once before the first execution of Update after the MonoBehaviour is created
|
||||
private void Start()
|
||||
{
|
||||
var clock = Clock.Instance;
|
||||
}
|
||||
|
||||
// Update is called once per frame
|
||||
//void Update()
|
||||
//{
|
||||
// if (Input.GetKeyUp(KeyCode.W))
|
||||
// {
|
||||
// SceneManager.LoadScene("SampleScene");
|
||||
// }
|
||||
// if (timer > 1)
|
||||
// {
|
||||
// timer -= 1;
|
||||
// Debug.Log("<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʱ<EFBFBD>ӳ<EFBFBD>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD>");
|
||||
// }
|
||||
// timer += Time.deltaTime;
|
||||
//}
|
||||
}
|
||||
}
|
@ -1,2 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: be939c7ca1c4f374b83b6535b3cbb656
|
@ -1,3 +1,6 @@
|
||||
using System;
|
||||
using Data;
|
||||
using Managers;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Test
|
||||
@ -6,11 +9,19 @@ namespace Test
|
||||
|
||||
public class TestDefine : MonoBehaviour
|
||||
{
|
||||
// Start is called once before the first execution of Update after the MonoBehaviour is created
|
||||
public EntityManage entityManager;
|
||||
void Awake()
|
||||
{
|
||||
Managers.DefineManager.Instance.Init();
|
||||
Debug.Log(Managers.DefineManager.Instance);
|
||||
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
var chicken = Managers.DefineManager.Instance.FindDefine<CharacterDef>("testPawn");
|
||||
entityManager.GenerateEntity(chicken,Vector3.zero);
|
||||
entityManager.GenerateDefaultEntity(Vector3.down);
|
||||
Debug.Log(chicken);
|
||||
}
|
||||
|
||||
// Update is called once per frame
|
||||
|
@ -1,5 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Data;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
@ -47,6 +48,8 @@ namespace UI
|
||||
{
|
||||
var button=InstantiatePrefab(buttonTemplate, menuContent.transform);
|
||||
button.Label = def.label;
|
||||
var pawnDef = def;
|
||||
button.AddListener(() => GenerateEntityCallback(pawnDef));
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -78,6 +81,10 @@ namespace UI
|
||||
return instantiatedComponent;
|
||||
}
|
||||
|
||||
void GenerateEntityCallback(PawnDef pawnDef)
|
||||
{
|
||||
Managers.EntityManage.Instance.GenerateEntity(pawnDef, new(0, 0));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
Reference in New Issue
Block a user