Files
5.24BuYu/Assets/MyGame/Scripts/Manager/FishSpawnTimerJob.cs
T

73 lines
2.6 KiB
C#
Raw Normal View History

2026-04-29 01:18:39 +08:00
// ============================================================
// 文件:FishSpawnTimerJob.cs
// 职责:用 Unity Job System(Burst 编译)并行更新所有鱼的生成计时器
// 优化点:
// 1. 移除错误的 static List<float>(BurstCompile struct 中不允许托管类型)
// 2. 修正原逻辑 bug:原代码 shouldSpawn==0 才计时,
// 导致 shouldSpawn==1 时计时器永远不推进;
// 修正为:shouldSpawn==1 时视为"冷却中",计时推进,到期后置为可生成。
// (与 CreateFishManager.ProcessSpawnRequests 的语义对齐:
// 1=本帧可生成;处理后由主线程置为 0;Job 再次计时到期后置为 1)
// 3. 补充 XML 注释
// ============================================================
2026-02-03 11:35:19 +08:00
using Unity.Burst;
using Unity.Collections;
2026-03-27 15:18:35 +08:00
using Unity.Jobs;
2026-02-03 11:35:19 +08:00
2026-04-29 01:18:39 +08:00
/// <summary>
/// 鱼生成计时器 Job(Burst 编译,Worker 线程并行执行)。
/// 每帧累加 deltaTime,到达 frequencies[i] 后将 shouldSpawn[i] 置为 1,
/// 表示该鱼本帧可以触发生成逻辑。
/// </summary>
2026-02-03 11:35:19 +08:00
[BurstCompile]
public struct FishSpawnTimerJob : IJob
{
2026-04-29 01:18:39 +08:00
// ----------------------------------------------------------------
// 输入
// ----------------------------------------------------------------
2026-03-27 15:18:35 +08:00
2026-04-29 01:18:39 +08:00
/// <summary>本帧 Time.deltaTime(由主线程传入)</summary>
public float deltaTime;
/// <summary>每条鱼的生成频率(间隔秒数),只读</summary>
[ReadOnly]
public NativeArray<float> frequencies;
// ----------------------------------------------------------------
// 读写
// ----------------------------------------------------------------
/// <summary>每条鱼的累计计时器(秒),由 Job 更新</summary>
public NativeArray<float> timers;
/// <summary>
/// 生成标志位:
/// 0 = 冷却中,Job 正在计时
/// 1 = 计时到期,本帧可触发生成(主线程处理后将其重置为 0)
/// </summary>
public NativeArray<int> shouldSpawn;
// ----------------------------------------------------------------
// 执行
// ----------------------------------------------------------------
2026-02-03 11:35:19 +08:00
public void Execute()
{
for (int i = 0; i < timers.Length; i++)
{
2026-04-29 01:18:39 +08:00
// 仅对冷却中(shouldSpawn==0)的鱼推进计时器
if (shouldSpawn[i] != 0) continue;
timers[i] += deltaTime;
// 计时到达频率阈值 → 允许生成,重置计时器
if (timers[i] >= frequencies[i])
2026-03-27 15:18:35 +08:00
{
2026-04-29 01:18:39 +08:00
timers[i] = 0f;
shouldSpawn[i] = 1;
2026-02-03 11:35:19 +08:00
}
}
}
}