(client) feat:做了初始化加载动画。 fix:修复定义加载列表和加载枚举时的错误识别

This commit is contained in:
m0_75251201
2025-08-17 23:01:43 +08:00
parent dea6cd5fa3
commit f67aca0804
18 changed files with 1247 additions and 39 deletions

View File

@ -0,0 +1,151 @@
using System;
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;
namespace Base
{
// 定义渐变方向枚举
[AddComponentMenu("UI/Effects/Gradient")]
public enum Dir
{
Horizontal, // 水平方向
Vertical, // 垂直方向
}
// 自定义梯度效果类继承自BaseMeshEffect
public class Gradient : BaseMeshEffect
{
[SerializeField] // 序列化字段可在Inspector中编辑
private Dir dir = Dir.Vertical; // 渐变方向,默认垂直
[SerializeField]
public Color32 color1 = Color.white; // 渐变起始颜色,默认白色
[SerializeField]
public Color32 color2 = Color.white; // 渐变结束颜色,默认白色
[SerializeField]
private float range = 0f; // 渐变范围,控制颜色的过渡区域,默认无范围(完全渐变)
[SerializeField]
private bool isFlip = false; // 是否翻转渐变方向,默认不翻转
public void Refresh()
{
graphic.SetVerticesDirty();
}
// 重写ModifyMesh方法用于修改UI元素的网格
public override void ModifyMesh(VertexHelper vh)
{
if (!IsActive()) // 如果组件未激活,则不执行后续操作
{
return;
}
var count = vh.currentVertCount; // 获取当前顶点数量
if (count > 0) // 如果有顶点,则进行处理
{
var vertices = new List<UIVertex>(); // 创建顶点列表
// 遍历所有顶点并添加到列表中
for (var i = 0; i < count; i++)
{
var uIVertex = new UIVertex();
vh.PopulateUIVertex(ref uIVertex, i); // 填充顶点信息
vertices.Add(uIVertex);
}
// 根据渐变方向调用相应的绘制方法
switch (dir)
{
case Dir.Horizontal:
DrawHorizontal(vh, vertices, count);
break;
case Dir.Vertical:
DrawVertical(vh, vertices, count);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
// 绘制垂直方向的渐变
private void DrawVertical(VertexHelper vh, List<UIVertex> vertices, int count)
{
// 初始化顶部和底部Y坐标
var topY = vertices[0].position.y;
var bottomY = vertices[0].position.y;
// 遍历所有顶点找到最高和最低的Y坐标
for (var i = 0; i < count; i++)
{
var y = vertices[i].position.y;
if (y > topY) topY = y;
else if (y < bottomY) bottomY = y;
}
var height = topY - bottomY; // 计算高度差
// 遍历所有顶点,设置颜色渐变
for (var i = 0; i < count; i++)
{
var vertex = vertices[i];
Color32 color = Color.white;
// 根据是否翻转,计算当前顶点的颜色
if (isFlip)
{
color = Color32.Lerp(color2, color1, 1 - (vertex.position.y - bottomY) / height * (1f - range));
}
else
{
color = Color32.Lerp(color2, color1, (vertex.position.y - bottomY) / height * (1f - range));
}
vertex.color = color; // 设置顶点颜色
vh.SetUIVertex(vertex, i); // 更新网格中的顶点
}
}
// 绘制水平方向的渐变
private void DrawHorizontal(VertexHelper vh, List<UIVertex> vertices, int count)
{
// 注意这里应该是找到最左和最右的X坐标注释中存在笔误
var leftX = vertices[0].position.x;
var rightX = vertices[0].position.x;
// 遍历所有顶点找到最左和最右的X坐标
for (var i = 0; i < count; i++)
{
var x = vertices[i].position.x;
if (x > rightX) rightX = x;
else if (x < leftX) leftX = x;
}
var width = rightX - leftX; // 计算宽度差
// 遍历所有顶点,设置颜色渐变
for (var i = 0; i < count; i++)
{
var vertex = vertices[i];
Color32 color = Color.white;
// 根据是否翻转,计算当前顶点的颜色
if (isFlip)
{
color = Color32.Lerp(color2, color1, 1 - (vertex.position.x - leftX) / width * (1f - range));
}
else
{
color = Color32.Lerp(color2, color1, (vertex.position.x - leftX) / width * (1f - range));
}
vertex.color = color; // 设置顶点颜色
vh.SetUIVertex(vertex, i); // 更新网格中的顶点
}
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8df3d16a358d74644b86e92ca5177fa1

View File

@ -0,0 +1,104 @@
using System.Collections;
using Logging;
using TMPro;
using UnityEngine;
namespace Base
{
public class Launcher : MonoBehaviour
{
public Gradient progressBar; // 渐变色条
public TMP_Text describeText; // 描述文本
private float _currentProgress = 0f; // 当前进度
private float duration = 0.5f; // 过渡时间
private string[] _loadingSteps =
{
"初始化日志", "正在载入定义", "正在加载图片资源", "正在切割瓦片", "正在加载区分派系",
"正在加载物品"
};
public float progress
{
set
{
_currentProgress = value;
if (value < 0.5f)
{
progressBar.color2 = Color.Lerp(Color.black, Color.white, value * 2);
}
else
{
progressBar.color2 = Color.white;
progressBar.color1 = Color.Lerp(Color.black, Color.white, (value - 0.5f) * 2);
}
progressBar.Refresh();
}
}
private void Start()
{
StartCoroutine(LoadAllManagers());
}
private IEnumerator LoadAllManagers()
{
for (var i = 0; i < _loadingSteps.Length; i++)
{
// 更新描述文本
describeText.text = _loadingSteps[i];
// 获取当前阶段的目标进度
var targetProgress = (float)(i + 1) / _loadingSteps.Length;
// 平滑过渡到下一个阶段
yield return SmoothTransitionTo(targetProgress);
// 初始化对应的管理器
switch (i)
{
case 0:
UnityLogger.Init();
break;
case 1:
Managers.DefineManager.Instance.Init();
break;
case 2:
Managers.PackagesImageManager.Instance.Init();
break;
case 3:
Managers.TileManager.Instance.Init();
break;
case 4:
Managers.AffiliationManager.Instance.Init();
break;
case 5:
Managers.ItemResourceManager.Instance.Init();
break;
}
}
// 加载完成后的处理
describeText.text = "加载完成!";
progress = 1f;
}
private IEnumerator SmoothTransitionTo(float targetProgress)
{
var startProgress = _currentProgress;
var elapsedTime = 0f;
while (elapsedTime < duration)
{
elapsedTime += Time.deltaTime;
var t = Mathf.SmoothStep(0f, 1f, elapsedTime / duration); // 使用 SmoothStep 实现平滑过渡
progress = Mathf.Lerp(startProgress, targetProgress, t);
yield return null;
}
// 确保最终进度达到目标值
progress = targetProgress;
}
}
}

View File

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 1966ff90f1854aee9ca89d700abef90d
timeCreated: 1755438497

View File

@ -8,11 +8,12 @@ namespace Data
Hostile,
Friendly,
}
public class AffiliationDef : Define
{
public Relation defaultRelation = Relation.Neutral;
public List<string> hostileFactions;
public List<string> neutralFactions;
public List<string> friendlyFactions;
public List<string> hostileFactions = new();
public List<string> neutralFactions = new();
public List<string> friendlyFactions = new();
}
}

View File

@ -1,4 +1,5 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
@ -279,10 +280,14 @@ namespace Data
value = reference;
}
}
else if(field.FieldType.IsArray)
else if(field.FieldType.IsArray||typeof(IList).IsAssignableFrom(field.FieldType))
{
value = ProcessArrayField(field, element);
}
else if (field.FieldType.IsEnum)
{
value = Enum.Parse(field.FieldType, element.Value);
}
else
{
value = Convert.ChangeType(element.Value, field.FieldType);
@ -291,13 +296,14 @@ namespace Data
}
catch (Exception ex)
{
Debug.LogWarning($"Error setting field {field.Name}: {ex.Message}");
Debug.LogWarning($"Error setting field ,field name:{field.Name}; value: {element.Value}; error: {ex.Message}");
}
}
}
private static object ProcessArrayField(FieldInfo field, XElement element)
{
Type elementType = field.FieldType.GetElementType();
var elementType = field.FieldType.GetElementType();
if (elementType == null) return null;
var arrayElements = new List<object>();
@ -305,7 +311,7 @@ namespace Data
{
if (elementType.IsSubclassOf(typeof(Define)))
{
Define nestedDefine = (Define)Activator.CreateInstance(elementType);
var nestedDefine = (Define)Activator.CreateInstance(elementType);
DefaultInitDefine(nestedDefine, liElement, elementType);
arrayElements.Add(nestedDefine);
}
@ -326,8 +332,8 @@ namespace Data
}
// 构建结果数组
Array resultArray = Array.CreateInstance(elementType, arrayElements.Count);
for (int i = 0; i < arrayElements.Count; i++)
var resultArray = Array.CreateInstance(elementType, arrayElements.Count);
for (var i = 0; i < arrayElements.Count; i++)
{
resultArray.SetValue(arrayElements[i], i);
}

View File

@ -11,7 +11,7 @@ namespace Data
public DrawingOrderDef drawingOrder;
public BehaviorTreeDef behaviorTree;
public string affiliation;
public AffiliationDef affiliation;
}

View File

@ -149,7 +149,7 @@ namespace Entity
{
attributes = entityDef.attributes.Clone();
aiTree = Utils.BehaviorTree.ConvertToAIBase(entityDef.behaviorTree);
affiliation = entityDef.affiliation;
affiliation = entityDef.affiliation.defName;
InitBody(entityDef.drawingOrder);
this.entityDef = entityDef;

View File

@ -0,0 +1,157 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Data;
namespace Managers
{
public class AffiliationManager:Utils.Singleton<AffiliationManager>
{
//定义名,阵营定义
private readonly Dictionary<string, AffiliationDef> _affiliations = new();
public void Init()
{
var affiliationList = Managers.DefineManager.Instance.QueryDefinesByType<AffiliationDef>();
if (affiliationList == null ||affiliationList.Length==0)
return;
foreach (var affiliation in affiliationList)
{
_affiliations.Add(affiliation.defName, affiliation);
}
ValidateAndFixRelationships();
}
public string GetAffiliationName(string defName)
{
return _affiliations[defName].defName;
}
public Relation GetRelation(string factionName1, string factionName2)
{
// 如果查询的是同一个派系,默认是友好关系
if (factionName1 == factionName2)
{
return Relation.Friendly;
}
// 尝试获取两个派系的定义
if (!_affiliations.TryGetValue(factionName1, out var faction1) ||
!_affiliations.TryGetValue(factionName2, out _))
{
if (faction1 != null) return faction1.defaultRelation;
return Relation.Neutral;
}
// 检查faction1是否明确将faction2列为敌对
if (faction1.hostileFactions != null && faction1.hostileFactions.Contains(factionName2))
{
return Relation.Hostile;
}
// 检查faction1是否明确将faction2列为友好
if (faction1.friendlyFactions != null && faction1.friendlyFactions.Contains(factionName2))
{
return Relation.Friendly;
}
// 检查faction1是否明确将faction2列为中立
if (faction1.neutralFactions != null && faction1.neutralFactions.Contains(factionName2))
{
return Relation.Neutral;
}
// 如果faction1没有明确设置与faction2的关系则使用faction1的默认关系
return faction1.defaultRelation;
}
/// <summary>
/// 设置两个阵营之间的关系
/// </summary>
/// <param name="factionName1">第一个阵营名称</param>
/// <param name="factionName2">第二个阵营名称</param>
/// <param name="relation">要设置的关系</param>
public void SetRelation(string factionName1, string factionName2, Relation relation)
{
// 不能设置自己与自己的关系
if (factionName1 == factionName2)
{
throw new ArgumentException("Cannot set relation between the same faction");
}
// 确保两个阵营都存在
if (!_affiliations.TryGetValue(factionName1, out var faction1) ||
!_affiliations.TryGetValue(factionName2, out _))
{
throw new ArgumentException("One or both factions do not exist");
}
// 确保关系列表已初始化
faction1.hostileFactions ??= new List<string>();
faction1.friendlyFactions ??= new List<string>();
faction1.neutralFactions ??= new List<string>();
// 先移除所有现有关系
faction1.hostileFactions.Remove(factionName2);
faction1.friendlyFactions.Remove(factionName2);
faction1.neutralFactions.Remove(factionName2);
// 添加新关系
switch (relation)
{
case Relation.Hostile:
faction1.hostileFactions.Add(factionName2);
break;
case Relation.Friendly:
faction1.friendlyFactions.Add(factionName2);
break;
case Relation.Neutral:
faction1.neutralFactions.Add(factionName2);
break;
default:
throw new ArgumentOutOfRangeException(nameof(relation), relation, null);
}
}
/// <summary>
/// 检查并修复派系关系,确保没有冲突(按友好 > 敌对 > 中立 的优先级)
/// </summary>
private void ValidateAndFixRelationships()
{
foreach (var faction in _affiliations.Values)
{
// 确保所有关系列表已初始化
faction.hostileFactions ??= new List<string>();
faction.friendlyFactions ??= new List<string>();
faction.neutralFactions ??= new List<string>();
// 检查所有敌对派系
foreach (var hostileFaction in faction.hostileFactions.ToList())
{
// 如果敌对派系同时存在于友好列表中,移除敌对关系(友好优先)
if (faction.friendlyFactions.Contains(hostileFaction))
{
faction.hostileFactions.Remove(hostileFaction);
continue;
}
// 如果敌对派系同时存在于中立列表中,移除中立关系(敌对优先)
if (faction.neutralFactions.Contains(hostileFaction))
{
faction.neutralFactions.Remove(hostileFaction);
}
}
// 检查所有中立派系
foreach (var neutralFaction in faction.neutralFactions.ToList())
{
// 如果中立派系同时存在于友好列表中,移除中立关系(友好优先)
if (faction.friendlyFactions.Contains(neutralFaction))
{
faction.neutralFactions.Remove(neutralFaction);
}
}
}
}
}
}

View File

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 31017ce35a6b441fb36e085dd3fd7c27
timeCreated: 1755407963

View File

@ -10,18 +10,15 @@ namespace Managers
public class EntityManage : Utils.MonoSingleton<EntityManage>, ITick
{
public Dictionary<string, LinkedList<EntityPrefab>> factionEntities = new();
public GameObject entityLevel;
public EntityPrefab entityPrefab;
public GameObject buildingLevel;
public EntityPrefab buildingPrefab;
public GameObject bulletLevel;
public EntityPrefab bulletPrefab;
public EntityPrefab defaultEntityPrefab;
private List<Tuple<string,EntityPrefab>> pendingAdditions;
private Dictionary<string, Transform> layerCache = new Dictionary<string, Transform>();
private List<Tuple<string, EntityPrefab>> pendingAdditions;
public LinkedList<EntityPrefab> FindEntitiesByFaction(string factionKey)
{
@ -71,6 +68,7 @@ namespace Managers
factionEntities[entity.Item1].AddLast(entity.Item2);
}
pendingAdditions.Clear();
}
}
@ -112,16 +110,8 @@ namespace Managers
extraInit?.Invoke(entityComponent);
// 管理派系列表
var factionKey = def.attributes.label ?? "default";
var factionKey = def.attributes.defName ?? "default";
pendingAdditions.Add(Tuple.Create(factionKey, entityComponent));
// if (!factionEntities.ContainsKey(factionKey))
// {
// factionEntities[factionKey] = new LinkedList<EntityPrefab>();
// }
// factionEntities[factionKey].AddLast(entityComponent);
return entityComponent;
}
catch (System.Exception ex)
@ -134,6 +124,34 @@ namespace Managers
}
}
/// <summary>
/// 动态创建层(如果层不存在)
/// </summary>
private Transform EnsureLayerExists(string layerName)
{
// 先从缓存中查找
if (layerCache.TryGetValue(layerName, out var layerTransform))
{
return layerTransform;
}
// 如果缓存中没有,尝试通过 transform.Find 查找
layerTransform = transform.Find(layerName);
if (!layerTransform)
{
// 如果层不存在,动态创建
var layerObject = new GameObject(layerName);
layerTransform = layerObject.transform;
layerTransform.SetParent(transform, false); // 将层附加到当前管理器下
}
// 将新创建的层加入缓存
layerCache[layerName] = layerTransform;
return layerTransform;
}
/// <summary>
/// 根据PawnDef生成普通实体
/// </summary>
@ -154,10 +172,13 @@ namespace Managers
return;
}
// 确保层存在
var entityLevelTransform = EnsureLayerExists("EntityLevel");
// 调用通用生成逻辑
var result = GenerateEntityInternal(
entityPrefab.gameObject,
entityLevel.transform,
entityLevelTransform,
pos,
entityDef
);
@ -187,14 +208,17 @@ namespace Managers
var worldPos = new Vector3(pos.x, pos.y, pos.z);
// 确保层存在
var buildingLevelTransform = EnsureLayerExists("BuildingLevel");
var result = GenerateEntityInternal(
buildingPrefab.gameObject,
buildingLevel.transform,
buildingLevelTransform,
worldPos,
buildingDef
);
if (!result) GenerateDefaultEntity(pos);
if (!result) GenerateDefaultEntity(worldPos);
}
/// <summary>
@ -217,9 +241,12 @@ namespace Managers
return;
}
// 确保层存在
var bulletLevelTransform = EnsureLayerExists("BulletLevel");
var result = GenerateEntityInternal(
bulletPrefab.gameObject,
bulletLevel.transform,
bulletLevelTransform,
pos,
bulletDef,
// 子弹特有的方向设置
@ -234,18 +261,16 @@ namespace Managers
/// </summary>
public void GenerateDefaultEntity(Vector3 pos)
{
var entity = Instantiate(defaultEntityPrefab, pos, Quaternion.identity, entityLevel.transform);
// 确保层存在
var entityLevelTransform = EnsureLayerExists("EntityLevel");
var entity = Instantiate(defaultEntityPrefab, pos, Quaternion.identity, entityLevelTransform);
var entityComponent = entity.GetComponent<EntityPrefab>();
const string factionKey = "default";
pendingAdditions.Add(Tuple.Create(factionKey, entityComponent));
// if (!factionEntities.ContainsKey(factionKey))
// {
// factionEntities[factionKey] = new LinkedList<EntityPrefab>();
// }
// entityComponent.DefaultInit();
// factionEntities[factionKey].AddLast(entityComponent);
entityComponent.DefaultInit();
}
protected override void OnStart()
@ -258,7 +283,7 @@ namespace Managers
{
var pre = Resources.Load<GameObject>("Default/DefaultEntity");
defaultEntityPrefab = pre.GetComponent<EntityPrefab>();
layerCache.Clear();
}
}
}

View File

@ -14,6 +14,8 @@ namespace Managers
public void Init()
{
var itemDefs = Managers.DefineManager.Instance.QueryDefinesByType<ItemDef>();
if(itemDefs==null||itemDefs.Length==0)
return;
foreach (var itemDef in itemDefs)
{
var item=new Item.ItemResource();