using UnityEngine;
using System.Collections.Generic;
///
/// 自动绑定友方英雄到UI卡片(Play Mode自动运行)
///
public class AutoBindHeroes : MonoBehaviour
{
[Header("UI引用")]
[Tooltip("英雄卡片面板的父物体")]
public Transform heroCardsPanel;
[Header("英雄头像资源")]
public Sprite soldierIcon;
public Sprite archerIcon;
public Sprite shieldIcon;
public Sprite mageIcon;
public Sprite eliteSoldierIcon;
private bool hasBindOnce = false;
void Start()
{
// 延迟1秒等待所有英雄生成
Invoke(nameof(BindHeroesToCards), 1f);
}
void BindHeroesToCards()
{
if (hasBindOnce)
{
Debug.LogWarning("英雄已经绑定过了,跳过重复绑定");
return;
}
if (heroCardsPanel == null)
{
Debug.LogError("AutoBindHeroes: heroCardsPanel 未赋值!");
return;
}
// 1. 查找所有友方英雄(teamId=0)
var allUnits = FindObjectsOfType();
var heroes = new List();
foreach (var unit in allUnits)
{
var team = unit.GetComponent();
if (team != null && team.teamId == 0)
{
heroes.Add(unit);
}
}
if (heroes.Count == 0)
{
Debug.LogWarning("AutoBindHeroes: 未找到友方英雄(teamId=0)");
return;
}
Debug.Log($"AutoBindHeroes: 找到 {heroes.Count} 个友方英雄");
// 2. 设置所有英雄为可复活
foreach (var hero in heroes)
{
var health = hero.GetComponent();
if (health != null)
{
health.canRevive = true;
}
}
// 3. 绑定到UI卡片(最多5个)
int bindCount = Mathf.Min(heroes.Count, 5);
for (int i = 0; i < bindCount; i++)
{
var hero = heroes[i];
var cardObj = heroCardsPanel.Find($"HeroCard{i + 1}");
if (cardObj == null)
{
Debug.LogWarning($"AutoBindHeroes: 未找到 HeroCard{i + 1}");
continue;
}
var heroCardUI = cardObj.GetComponent();
if (heroCardUI == null)
{
Debug.LogWarning($"AutoBindHeroes: HeroCard{i + 1} 缺少 HeroCardUI 组件");
continue;
}
// 根据英雄名字匹配头像
Sprite icon = GetHeroIcon(hero.name);
if (icon == null)
{
Debug.LogWarning($"AutoBindHeroes: {hero.name} 没有匹配的头像,使用默认图标");
}
// 绑定英雄
heroCardUI.SetHero(hero, icon, hero.transform.position);
Debug.Log($"✅ HeroCard{i + 1} 已绑定: {hero.name}");
}
hasBindOnce = true;
Debug.Log($"✅ 英雄自动绑定完成!共绑定 {bindCount} 个英雄");
}
///
/// 根据英雄名字获取对应头像
///
Sprite GetHeroIcon(string heroName)
{
if (heroName.Contains("人类士兵") || heroName.Contains("士兵"))
{
return soldierIcon;
}
else if (heroName.Contains("弓箭手") || heroName.Contains("弓箭"))
{
return archerIcon;
}
else if (heroName.Contains("盾卫"))
{
return shieldIcon;
}
else if (heroName.Contains("法师"))
{
return mageIcon;
}
else if (heroName.Contains("精锐"))
{
return eliteSoldierIcon;
}
return null;
}
}