继承方式,代码更规范
父类
using System;
using UnityEngine;
namespace Production
{
public abstract class ProductionBuilding : MonoBehaviour
{
// 生产产品ID
public int productId = -1;
// 生产周期
public int productPeriod = 7;
// 生产数量
public int productCount = 5;
// 维护费用
public int costMoney = 5;
// 生长周期
public int growPeriod = -1;
// 是否已长大
protected bool IsGrown;
// 是否需要生长(growPeriod > 0)
protected bool IsNeedGrow;
// 已经过去的天数
protected int PassingDays;
public int GrownRemainingDays()
{
// 成熟剩余天数
return growPeriod - PassingDays - 1;
}
public int ProductRemainingDays()
{
// 生产剩余天数
return productPeriod - PassingDays - 1;
}
protected virtual void Awake()
{
WorldTimer.DoThisDay += NewDay;
IsNeedGrow = growPeriod > 0;
}
public bool IsGrowing()
{
// 正在生长:如果生长周期 > 0,且没有长大(默认),且过去的天数不大于生长周期
// 否则,返回没有在生长了
return growPeriod > 0 && !IsGrown && PassingDays <= growPeriod;
}
// 每个子类需要重写每天的过法
protected abstract void NewDay();
protected virtual void OnDestroy()
{
WorldTimer.DoThisDay -= NewDay;
}
}
}
农场类
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Production
{
public class Farm : ProductionBuilding
{
// 到达阶段2的天数
public int stage2 = 2;
// 到达阶段3的天数
public int stage3 = 3;
// 当前阶段
private int _currentStage = 1;
// 当前显示的阶段
private int _showingStage = 1;
private readonly Dictionary<int, GameObject> _stages = new Dictionary<int, GameObject>();
protected override void Awake()
{
base.Awake();
for (var i = 1; i <= 3; i++)
{
// 加载不同阶段
_stages[i] = transform.Find(i.ToString()).gameObject;
if (i >= 2)
{
_stages[i].SetActive(false);
}
}
}
private void Update()
{
// 如果当前显示场景等于当前场景,不处理
if (_showingStage == _currentStage) return;
// 否则,当前显示场景隐藏,显示当前场景
_stages[_showingStage].SetActive(false);
_stages[_currentStage].SetActive(true);
// 当前显示场景等于当前场景
_showingStage = _currentStage;
}
protected override void NewDay()
{
// 农场无条件直接过一天
PassingDays += 1;
if (IsNeedGrow && !IsGrown)
{
// 如果需要生长且没长大,处理成长逻辑
if (PassingDays < growPeriod) return;
IsGrown = true;
PassingDays = 0;
}
else
{
// 如果已经长大了,处理生产逻辑
// 注意这里当前阶段,需要生长的直接跳过第一阶段(如:苹果树)
_currentStage = PassingDays < stage2 && !IsNeedGrow ? 1 : PassingDays < stage3 ? 2 : 3;
if (PassingDays < productPeriod) return;
InstanceManager.Instance.knapsack.AddGoods(productId, productCount);
_currentStage = 1;
PassingDays = 0;
}
}
}
}
牧场类
using System;
namespace Production
{
public class Pasture : ProductionBuilding
{
// 消耗的产品ID
public int consumeProductId;
// 消耗的数量
public int consumeCount;
// 食物是否足够,用于UI展示
public bool NoFood { get; private set; } = true;
protected override void NewDay()
{
// 减少食物,食物不足不算一天
var consumeSuccess = InstanceManager.Instance.knapsack.AddGoods(consumeProductId,consumeCount * -1);
NoFood = !consumeSuccess;
if (NoFood) return;
// 成长和生产
PassingDays += 1;
if (IsNeedGrow && !IsGrown)
{
if (PassingDays < growPeriod) return;
IsGrown = true;
PassingDays = 0;
}
else
{
if (PassingDays < productPeriod) return;
InstanceManager.Instance.knapsack.AddGoods(productId, productCount);
PassingDays = 0;
}
}
}
}