128 lines
3.4 KiB
C#
128 lines
3.4 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
public class Barracks : MonoBehaviour
|
|
{
|
|
[Header("角色数据")]
|
|
public CharacterData characterData;
|
|
|
|
[Header("阵营")]
|
|
public string unitTag = "Friend";
|
|
|
|
[Header("生产设置")]
|
|
public Transform spawnPoint; // 单位生成位置
|
|
|
|
[Header("UI显示")]
|
|
public Image progressBar; // 生产进度条
|
|
public Image characterIcon; // 角色头像
|
|
|
|
private float spawnTimer = 0f;
|
|
private float spawnInterval = 5f;
|
|
private bool isProducing = true;
|
|
private BuildingHealth buildingHealth;
|
|
|
|
private void Start()
|
|
{
|
|
buildingHealth = GetComponent<BuildingHealth>();
|
|
|
|
if (characterData != null)
|
|
{
|
|
spawnInterval = 5f;
|
|
|
|
// 设置角色头像
|
|
if (characterIcon != null && characterData.cardIcon != null)
|
|
{
|
|
characterIcon.sprite = characterData.cardIcon;
|
|
}
|
|
|
|
Debug.Log($"兵营初始化:{characterData.characterName},生产间隔{spawnInterval}秒");
|
|
}
|
|
else
|
|
{
|
|
Debug.LogError("兵营缺少角色数据!");
|
|
}
|
|
|
|
// 如果没有spawnPoint,使用兵营自己的位置
|
|
if (spawnPoint == null)
|
|
{
|
|
spawnPoint = transform;
|
|
}
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (!isProducing || characterData == null) return;
|
|
|
|
spawnTimer += Time.deltaTime;
|
|
|
|
// 更新进度条
|
|
if (buildingHealth != null)
|
|
{
|
|
buildingHealth.SetProductionProgress(spawnTimer / spawnInterval);
|
|
}
|
|
else if (progressBar != null)
|
|
{
|
|
progressBar.fillAmount = spawnTimer / spawnInterval;
|
|
}
|
|
|
|
// 时间到,生产单位
|
|
if (spawnTimer >= spawnInterval)
|
|
{
|
|
SpawnUnit();
|
|
spawnTimer = 0f;
|
|
}
|
|
}
|
|
|
|
private void SpawnUnit()
|
|
{
|
|
if (characterData == null || characterData.unitPrefab == null)
|
|
{
|
|
Debug.LogError("无法生产单位:缺少unitPrefab");
|
|
return;
|
|
}
|
|
|
|
// 在spawnPoint位置生成单位
|
|
Vector3 spawnPosition = spawnPoint.position;
|
|
|
|
GameObject unit = Instantiate(characterData.unitPrefab, spawnPosition, Quaternion.identity);
|
|
unit.name = characterData.characterName;
|
|
unit.tag = unitTag;
|
|
|
|
// 设置阵营 ID(根据建筑的阵营)
|
|
var buildingTeam = GetComponent<UnitTeam>();
|
|
var unitTeam = unit.GetComponent<UnitTeam>();
|
|
if (buildingTeam != null && unitTeam != null)
|
|
{
|
|
unitTeam.teamId = buildingTeam.teamId;
|
|
}
|
|
else if (unitTeam != null)
|
|
{
|
|
// 兜底:根据 tag 判断阵营
|
|
unitTeam.teamId = unitTag == "Friend" ? 0 : 1;
|
|
}
|
|
|
|
// 如果单位有UnitBase组件,使用1级属性初始化
|
|
var unitBase = unit.GetComponent<UnitBase>();
|
|
if (unitBase != null)
|
|
{
|
|
float health = characterData.GetMaxHealth(1);
|
|
float attack = characterData.GetAttackPower(1);
|
|
float moveSpeed = characterData.GetMoveSpeed(1);
|
|
|
|
unitBase.InitializeFromPlayerData(health, attack, moveSpeed);
|
|
}
|
|
|
|
Debug.Log($"兵营生产了单位:{characterData.characterName}");
|
|
}
|
|
|
|
public void StopProduction()
|
|
{
|
|
isProducing = false;
|
|
}
|
|
|
|
public void StartProduction()
|
|
{
|
|
isProducing = true;
|
|
}
|
|
}
|