游戏客户端架构 / 系统课时
取出对象时要做哪些处理
取出对象时要做哪些处理
对象池真正容易出错的地方不是“拿到一个实例”,而是拿到后是否把它恢复成这一次使用应有的状态。位置、旋转、父节点、激活标记和业务数据如果有一项沿用旧值,就会出现子弹从旧位置飞出、特效挂错节点或伤害参数串场的问题。
学习目标
- 明确对象从空闲态切换到使用态时的处理顺序
- 重置位置、旋转、父节点和本次业务数据,避免旧状态泄漏
- 用可执行示例验证同一个实例可以安全地被多次借出
取出不是简单地出队
从容器拿到实例后,应先完成“结构重置”,再写入“本次数据”,最后才激活。推荐顺序是:设置新的父节点、设置位置和旋转、写入本次业务数据、切换为 Active。
这样安排的原因是,激活往往意味着更新逻辑、碰撞或事件监听开始工作。如果先激活,再慢慢修改位置和数据,就可能让对象在一帧内以旧状态参与游戏。

把本次使用数据集中传入
不要让调用方在取出后再零散设置十几个字段。更稳妥的做法是定义一个“出生参数”对象,把位置、旋转、父节点和业务数据作为一次借出所需的完整输入。这样既能固定初始化顺序,也更容易做校验。
下面的示例使用纯 C# 实现一个可运行的静态对象池。Acquire 会把旧实例从空闲队列取出,并在激活前重置全部关键状态。
using System;
using System.Collections.Generic;
using System.Numerics;
sealed record SpawnData(
Vector3 Position,
float RotationDegrees,
string Parent,
int Damage);
sealed class Bullet
{
public int Id { get; }
public bool Active { get; private set; }
public Vector3 Position { get; private set; }
public float RotationDegrees { get; private set; }
public string Parent { get; private set; } = "PoolRoot";
public int Damage { get; private set; }
public Bullet(int id)
{
Id = id;
}
public void Activate(SpawnData data)
{
// 先覆盖所有可能残留的结构和业务状态,再进入运行态。
Parent = data.Parent;
Position = data.Position;
RotationDegrees = data.RotationDegrees;
Damage = data.Damage;
Active = true;
}
public void Deactivate()
{
Active = false;
Parent = "PoolRoot";
Damage = 0;
}
}
sealed class BulletPool
{
private readonly Queue<Bullet> idle = new();
public BulletPool(int preloadCount)
{
if (preloadCount <= 0)
throw new ArgumentOutOfRangeException(nameof(preloadCount));
for (int i = 1; i <= preloadCount; i++)
idle.Enqueue(new Bullet(i));
}
public Bullet Acquire(SpawnData data)
{
if (idle.Count == 0)
throw new InvalidOperationException("Pool exhausted.");
Bullet bullet = idle.Dequeue();
bullet.Activate(data);
return bullet;
}
public void Release(Bullet bullet)
{
if (bullet is null)
throw new ArgumentNullException(nameof(bullet));
bullet.Deactivate();
idle.Enqueue(bullet);
}
}
static class Program
{
static void Main()
{
var pool = new BulletPool(preloadCount: 1);
Bullet first = pool.Acquire(
new SpawnData(new Vector3(10, 0, 0), 90, "WeaponA", 20));
Console.WriteLine($"{first.Id}: {first.Parent}, {first.Position.X}, {first.RotationDegrees}, {first.Damage}");
pool.Release(first);
Bullet second = pool.Acquire(
new SpawnData(new Vector3(2, 0, 0), 180, "WeaponB", 50));
Console.WriteLine($"{second.Id}: {second.Parent}, {second.Position.X}, {second.RotationDegrees}, {second.Damage}");
Console.WriteLine($"Same instance: {ReferenceEquals(first, second)}");
}
}预期输出:
1: WeaponA, 10, 90, 20
1: WeaponB, 2, 180, 50
Same instance: True同一个 Id=1 被连续借出两次,但第二次的位置、旋转、父节点和伤害值都来自新的 SpawnData。这正是对象池复用时需要保证的性质:复用实例,不复用上一次业务状态。
处理旧状态时要有明确边界
并不是所有字段都应该由通用池直接重置。通用池负责保存、取出和归还实例;像“剩余穿透次数”“特效颜色”“阵营编号”这类业务字段,应由具体对象自己的激活方法处理。否则池会逐渐知道太多业务细节,最后变成难维护的巨型管理器。
同时,归还阶段也要和取出阶段配对。某个字段如果在使用过程中会变化,就要明确它是在 Release 时清空,还是在下次 Acquire 时覆盖。只要没有确定规则,就迟早会留下脏状态。
验证是否真的没有串状态
测试时不要只借出一次。最容易暴露问题的方式,是只预热一个实例,连续执行“取出 → 修改 → 归还 → 再取出”,然后检查第二次是否完全使用新参数。只要同一个对象能反复经历这条链路而不携带旧数据,取出阶段的职责边界就基本跑通了。