GC 看不见你的 chunk The GC Cannot See Your Chunks
为什么放在片段里的 UObject 指针会突然变空,以及正确姿势 · 2026-11-21Why a UObject pointer inside a fragment goes null, and the shape that does not · 2026-11-21
系列这些文章写给人和他的 agent 一起看。这套文档怎么读 →SeriesThese posts are for you and your agent. How to read these docs →
那个坑:先好好的,然后突然空指针 The Trap: It Works, Then It Does Not
做音效生成的时候,我把一个声音资产的指针塞进了片段,让每个单位自己记住"我该放哪段声音"。一开始一切正常,音效按预期播出来,测了很久都没出事。然后某一天它崩了,崩在空指针上:我明明填过,怎么会是空?
I was building sound spawning and put a pointer to a sound asset inside a fragment, so each unit could remember which sound it plays. Everything worked, sounds played as expected, and it held up through a lot of testing. Then one day it crashed on a null pointer: I filled it in myself, how is it null?
同样一个指针放进 Actor,从来没出过事。差别在于有没有东西替你担保它还活着,跟指针本身无关。
The same pointer on an actor never caused trouble. What differs is whether anything vouches that the object is still alive, not the pointer.
GC 的世界里只有一件事:可达性 In the GC's World There Is Only Reachability
虚幻的垃圾回收从一组根往外走:从根出发,顺着所有登记过的引用(UPROPERTY、容器、委托……)能走到的对象算活的,走不到的回收。
Unreal's garbage collector walks outward from a set of roots. Anything reachable from a root through registered references (UPROPERTY, containers, delegates…) is alive; anything unreachable is collected.
指针放在 Actor 里之所以安全,是因为那个 UPROPERTY 把这条引用登记进了图里:GC 顺着 Actor 走到你的声音资产,判定可达,收不掉。片段的存储是另一回事,那是 Mass 自己管的一块裸内存,里面放了什么、指向谁,GC 一概不知道。
A pointer on an actor is safe because that UPROPERTY registered the reference into the graph: the GC walks from the actor to your sound asset, marks it reachable, and leaves it alone. A fragment's storage is something else: raw memory that Mass manages itself, where the GC cannot see what sits in it or what it points to.
于是有了那个"突然":没有东西替你保活,也没有东西会来通知你。对象被回收之后,你手里那个指针不再指向活物,等到某个 tick 真去用它,就崩在空指针上。它没填错,也没人清空,只是从头到尾没人担保过。
Hence the "suddenly": nothing kept it alive, and nothing was going to tell you. Once the object is collected, the pointer refers to nothing alive, and the tick that finally uses it crashes on a null. Nothing was filled in wrong and nothing cleared it — nothing had guaranteed it in the first place.
为什么这件事在 ECS 里格外容易踩 Why This Bites Harder in an ECS
对象世界里,这份保护是编译器替你做的:写个 UPROPERTY 就登记完了,你几乎不用想 GC 的事。ECS 为了性能把内存管理收回自己手里,连续布局、块拷贝、按原型迁移,代价就是那份自动登记没有了。
In an object world the compiler does that protection for you: write a UPROPERTY and the registration is done, and you barely think about the GC. An ECS takes memory management back for performance (contiguous layout, chunk copies, archetype migration), and the price is that the automatic registration is gone.
这是速度的代价,形状很坏:它不会在你写代码那天报错,会等你上线之后的某个随机时刻再报。这条只能靠纪律,预感没用。
That is the price of the speed, and it has a nasty shape: it does not fail the day you write the code, it fails at some random moment after you ship. A rule, then, not a hunch.
正确的形状:软路径当权威,片段外放一个持有者 The Right Shape: Soft Path for Authority, a Holder Outside the Fragment
把权威和担保分开,各自放到该在的地方,一共三块:
Split authority from the guarantee, and put each where it belongs — three pieces:
| 放哪Where | 放什么What | 为什么Why |
|---|---|---|
| 配置里(可序列化字段)In the config (serialisable field) | 软路径(软对象指针)A soft path (soft object pointer) | 它不进 GC 图,也不怕被回收:需要时按路径加载。它能序列化,跨端一致,适合作权威It stays out of the GC graph and cannot be collected: load by path when needed. It serialises and agrees across peers, which makes it the authority |
| 运行时:片段外的一个持有者At run time: a holder outside the fragment | 内容资产和世界里的对象,全部用 TStrongObjectPtr 钉住Pinned by TStrongObjectPtr — all of it, content assets and world-owned objects alike |
它是 GC 根:一个资产一份引用,跟实体数量无关。根不会自己消失,所以世界结束时要整表清一次A GC root: one reference per asset, independent of entity count. A root never expires on its own, so the table is cleared once when the world ends |
| 片段里In the fragment | 解析后的指针,只当"顺手可用"The resolved pointer, used only as a convenience | 它是缓存,权威永远在软路径那一侧A cache, never the authority; the authority stays on the soft-path side |
我们自己的代码就是这么摆的。注册表里的值全部是 TStrongObjectPtr,每张表里一个资产只有一份引用,片段里只留解析好的指针。世界结束的时候,PIE 停止、换图、Deinitialize,整张表清空,根一次放掉。一句话:片段里可以放指针,但片段外得有个持有者握着它,而持有者只有一种写法。否则又是那个坑:指针还在,担保没有。
Our own code is laid out this way. Every value in the registry is a TStrongObjectPtr, one reference per asset per table, and the fragment keeps only the resolved pointer. When the world ends (PIE stopping, a map change, Deinitialize), the tables are emptied and every root released at once. One sentence: a fragment may hold a pointer, but a holder outside the fragment must hold it, and there is only one way to write that holder. Skip it and you are back in the trap: a pointer in good order with no insurance behind it.
担保只有一种给法:把对象标成 GC 根 One Way to Vouch: Flag the Object as a GC Root
前面那句"GC 看不见 chunk 内存"说的是默认情况:放进去的是裸指针,外面没有任何东西握着。担保跟指针裸不裸无关。这里有两个轴,别混为一谈。软路径和强引用是分工,一个回答"是哪个资产",一个回答"它还活着";强引用只有一种实现,就是下面这个。
"The GC cannot see chunk memory" describes the default case: a raw pointer with nothing outside holding it. Whether the pointer is raw has nothing to do with the guarantee. Two axes are in play, keep them apart: soft path and strong reference divide the labour, one says which asset, the other says it is still alive; and the strong reference has exactly one implementation, below.
TStrongObjectPtr 不走引用图。构造时给对象加一次引用计数,同时把它标成 GC 的根(root),从此图里有没有人引用它,GC 都不碰;析构时把计数还回去。对象确实"被看见了",看见它的是根标记,引用图没参与。注册表里每张表的每个值都是它,内容资产和世界里的对象一样。
TStrongObjectPtr does not rely on the reference graph. Construction adds a reference count and flags the object as a GC root, and after that the collector leaves it alone whether or not anything else references it; destruction hands the count back. The object is seen, by the root flag rather than by the graph. Every value of every registry table is one, content assets and world-owned objects alike.
两条硬约束,都是踩出来的。一、持有者不能放在 chunk 内存里。Mass 迁移实体时整块按位拷贝,构造和析构都不跑,智能指针的加减计数会整体错掉。所以它只能待在外面的持有者身上,配置、子系统或模板,绝不能写成片段里的字段。
Two hard constraints, both learned by crashing into them. One: the holder cannot live in chunk memory. Mass moves entities by bit-copying the whole block, running no constructors or destructors, so the smart pointer's count would drift away from reality. It belongs to the holder outside the fragment — config, subsystem or template — never to a field inside one.
二、根是一份跨世界的承诺,必须自己放。被钉住的对象在世界拆掉时也不会被回收;钉的是世界里的对象,还会顺着 Outer 链把那个 world 一起钉住。编辑器的 PIE 结束流程正好踩在这上面:它先广播 EndPlayMapDelegate,再收垃圾,收完立刻检查 PIE 世界里还有没有活着的对象,有就断言 from PIE level still referenced。所以我们在那个 delegate 上挂一次清表,Deinitialize 再兜一次。少了这一步,PIE 一停就崩,实测的,不是理论推导。
Two: a root is a promise that crosses worlds, so you release it yourself. A pinned object survives its world being torn down, and pinning a world-owned object pins that world through its Outer chain. The editor's end-of-PIE path runs straight into it: it broadcasts EndPlayMapDelegate before collecting, then checks whether anything of the PIE world is still alive, and asserts from PIE level still referenced if something is. So we clear the tables from that delegate and catch it again in Deinitialize. Skip that and PIE crashes on stop — measured, not theorised.
换来的是一条规则、一个释放点。代价也说清楚:世界运行期间不释放任何资产,内存一路涨到世界结束。加载是毫秒级的时候这么换划算;哪天内容大到不能这么放,要动的是释放时机,不用再加一种持有方式。
What that buys is one rule and one release point. The price is explicit: nothing is released while the world runs, so memory climbs until the world ends. With millisecond loads that is the right trade; if content ever outgrows it, change when you release, do not invent another kind of holder.
由此得到的两条纪律 Two Rules That Follow
一、片段里优先放索引、句柄、软路径,对象指针往后排。热数据内联在片段里没问题,数字、向量、定长数组都行。但凡要"指向一个 UObject",先问两句:这东西会被序列化吗?需要跨端一致吗?两个都答"是",它就该是软路径或名字。
One: prefer indexes, handles and soft paths in fragments; keep object pointers out if you can. Hot data inline in a fragment is fine — numbers, vectors, fixed arrays. Anything that points at a UObject has to answer two questions first: will this be serialised, and must it agree across peers? Yes to both means a soft path or a name.
二、真要放对象指针,先回答"片段外谁握着它"。答案只有一个:某个 TStrongObjectPtr 钉住它,那个持有者活得比世界长,世界结束时被一起清掉。答不出来就别放。我们代码里那张通知表的注释写得很直白:这里只放软路径或名字,因为 GC 不扫描块内存,裸指针会被回收,而下面还有 agent 在用。
Two: if you do store an object pointer, answer "who holds it outside the fragment" first. There is one answer: a TStrongObjectPtr pins it, and that holder outlives the world, so it is cleared together with the world. No answer, no pointer. The comment on our notify table says it plainly: hold only soft paths or names here, because the GC does not scan chunk memory, so a raw pointer gets collected while agents below are still using it.
怎么确认"就是 GC" How to Confirm It Really Is the GC
这类崩溃有几个很好认的指纹:能跑很久才崩,一加载不会崩;崩在"用到"那一刻,"存进去"那一刻不崩;崩溃点跟资源加载的时机没有直接关系;同一份代码换台机器、换次运行,崩的位置还可能不同。
The fingerprints are easy to recognise: it runs a long time before failing, never on load; it fails where the pointer is used, not where it was stored; the crash site has no direct link to when the asset loaded; and another machine or another run may crash somewhere else.
最直接的验证:在怀疑的位置之前手动触发一次垃圾回收,紧接着用那个指针。从"偶尔崩"变成"每次都崩",就不用再猜了,问题在所有权。
The most direct check: force a garbage collection just before the suspect point, then use the pointer right away. If "occasionally" turns into "every time", stop guessing — the problem is ownership.
一句话 In One Line
指针本身没问题,缺的是有人担保它指向的对象还活着。在一个自动管内存的引擎里用一块手动管的内存,这份担保要自己补:软路径当权威,片段外用 TStrongObjectPtr 钉住,世界结束时整表清空,片段里那份指针只当缓存。
The pointer is fine; nothing vouches that its target is still alive. Using manually managed memory inside an engine that manages memory automatically means supplying that guarantee yourself: a soft path as the authority, a TStrongObjectPtr holding it outside the fragment, one clear of the tables when the world ends, and the pointer inside the fragment as a cache and nothing more.