Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

何时以及如何避免为任何事情使用节点

虽然节点的创建成本很低,但是它们也有一定的局限性。一个项目可能有成千上万个节点,都各自在做事情。每个节点的行为越复杂,对项目性能增加的压力就越大。

Godot 为创建节点使用的 API 提供了更轻量级的对象。在设计如何构建项目的特性时,请务必将这些作为选项牢记在心。

  1. Object:终极轻量级对象,原始的 Object 必须使用手动内存管理。尽管如此,创建自己的自定义数据结构——甚至是节点结构——也并不难,并且比 Node 类更轻量。

    • 示例:参见 Tree 节点。它支持对具有任意行数和列数的内容表,进行高级定制。用来生成可视化的数据实际上是 TreeItem 对象的树。

    • 优势: 将 API 简化为较小范围的对象,有助于提高其可访问性、改善迭代时间。与其使用整个 Node 库,不如创建一组简略的 Object,节点可以从这些 Object 中生成和管理相应的子节点。

    备注

    处理它们时要小心. 可以将 Object 存储到变量中, 但是这些引用可能在没有警告的情况下失效. 例如, 如果对象的创建者决定删除它, 这将在下一次访问时, 触发错误状态.

  2. RefCounted: Only a little more complex than Object. They track references to themselves, only deleting loaded memory when no further references to themselves exist. These are useful in the majority of cases where one needs data in a custom class.

    • Example: See the FileAccess object. It functions just like a regular Object except that one need not delete it themselves.

    • 优势:Object 相同.

  3. Resource: Only slightly more complex than RefCounted. They have the innate ability to serialize/deserialize (i.e. save and load) their object properties to/from Godot resource files.

    • 示例 : 脚本, PackedScene (用于场景文件), 以及其他类型, 比如 AudioEffect 类. 每一个都可以保存和加载, 因此它们从 Resource 扩展.

    • Advantages: Much has already been said on Resource's advantages over traditional data storage methods. In the context of using Resources over Nodes though, their main advantage is in Inspector-compatibility. While nearly as lightweight as Object/RefCounted, they can still display and export properties in the Inspector. This allows them to fulfill a purpose much like sub-Nodes on the usability front, but also improve performance if one plans to have many such Resources/Nodes in their scenes.