---
title: 对象池和重用
product: Unity Editor
version: '6000.0'
latest_version: '7000.0'
status: This page documents version 6000.0. The latest version is 7000.0.
canonical: https://docs.unity.com/zh-cn/engine/6000.0/manual/scripting/optimization/performance-optimizing-code-managed-memory/reusable-code
latest_url: https://docs.unity.com/zh-cn/engine/7000.0/manual/scripting/optimization/performance-optimizing-code-managed-memory/reusable-code.md
generated_at: 2026-11-16T08:43:16.355Z
locale: zh-cn
---

# 对象池和重用

> 通过使用 Unity 的 池 API 可减少 CPU 加载和垃圾回收器开销，这些 API 允许您池和重用常用对象，而不是重复创建和销毁它们。

对象池和重用是一种编程模式，它将常用对象的实例返回到池，然后可以从中检索和再次使用它们。Object池可以减少反复实例化和销毁新建Object实例导致的开销，并限制分配和取消分配的数量。这有助于最大限度减少垃圾Collection GC 开销并减少 CPU ON的加载。

您可以池游戏对象对象，但也可以池经常使用的Other类型，包括Collection类型，例如数组、列表和字典。您可以编写自己的池逻辑，但为了方便起见，Unity 在 `UnityEngine.Pool` 命名空间中提供了一组 API，其中包含池化游戏对象的实现和几种 Collection 类型。

> **Note:**
>
> 与许多其他核心 Unity API 一样，`UnityEngine.Pool` API 不是线程安全的，只能从主要线程安全地调用。

## 池化和重用游戏对象##pooling-and-reusing-gameobjects

游戏中的某些类型对象（例如飞弹）可能会反复出现并经常出现，即使它们中只有少数对象曾经时间出现在Scene中。不必在时间发射时从预制件件实例新建的飞弹Object，而是可以在游戏Start时创建一个飞弹对象池，然后根据需要重用它们。

### 创建对象池##creating-an-object-pool

Unity 的 [`ObjectPool<T>`](/engine/6000.0/script-reference/unityengine/pool/objectpool1.md) 类提供了可重用对象池模式的实现，是在应用程序中实现对象池的最简单方法。`ObjectPool<T>` 实例管理`T`类型对象的池。当您通过 [`ObjectPool<T>` 构造函数](/engine/6000.0/script-reference/unityengine/pool/objectpool1/ctor.md)创建`ObjectPool<T>`时，您需要提供参数来定义池的以下 Key 方面：

* 池的起始容量。

* 池可以扩展到的最大容量。

* 是否执行Collection安全检查以防止将同一Object实例再次释放池。

* 一系列 C# [`Action<T>`](https://learn.microsoft.com/en-us/dotnet/api/system.action-1?view=net-10.0)委托，这是 Unity 在池上执行以下 Key 操作时调用的回调：

  * 从池检索ObjectON要调用的回调。
  * 将对Object回到池ON调用的回调。
  * 在请求新建 Object 实例并且池为空时 ON 调用的回调。
  * WhenObject池池实例调用的回调。

### 从池检索对象##retrieving-objects-from-the-pool

调用 [`ObjectPool<T>.Get`](ScriptRef:ScriptRef:Pool.ObjectPool_1.Get) 从池中检索对象。此 Action 还会调用您作为 `ObjectPool` 构造函数的 `actionOnGet` 参数提供的方法，这使您能够准备和激活 Object 以供使用。

如果在池空空ject，则会创建一个新建的Object实例。创建过程会调用您作为 `createFunc` 参数提供给 `ObjectPool` 构造函数的方法。

`ObjectPool<T>.Get` 具有重载`Get(out PooledObject<T> pooledObject)`。当处置`PooledObject`时，它会自动释放实例。这对于短暂作用域很有用。

有关更多信息和代码示例，请参阅[`PooledObject<T>.Get` API 参考](ScriptRef:Pool.PooledObject_1.Get)。

### 将对象返回到池##returning-objects-to-the-pool

当您使用完 Object 后，通过调用 [`ObjectPool<T>.Release`](/engine/6000.0/script-reference/unityengine/pool/objectpool1/release.md) 并将其作为参数返回给池。此 Action 还会调用您作为 `ObjectPool` 构造函数的 `actionOnRelease` 参数提供的方法，因此您可以停用和重置返回对象的 ON 状态。

如果在池已When将对Objectject回到池，则对Object将被销毁。销毁过程会调用您作为 `actionOnDestroy` 参数提供给 `ObjectPool` 构造函数的方法。

将 `true` 作为 `collectionCheck` 参数传递给构造函数可启用 Collection 安全检查。如果已启用了Collection检查并尝试返回池中已有的Object，Unity 会抛出异常。即使已启用，Collection 检查仅在 Editor 中可用，在 Player 构建中不可用。启用 Collection 检查会增加开销，但会捕获双释放错误，建议在 Development 期间启用。

### 重置使用的对象##resetting-used-objects

池中检索的对象可能会在使用过程中更Change其状态。例如，池化敌人游戏对象对象在Scene中处于Active状态时可能会Change其位置、Health值、Animation State和Physics状态。WhObjectOb池ect池Reset此状态非常重要，以便稍后再次获取When，其启动状态与第一次使用ON相同。

根据重置的状态，可以选择在从 `actionOnGet` 委托中的池获取对象时重置该对象，或者当将其释放回 `actionOnRelease` 委托中的池时重置该对象。另一种选项是ON池对Object身上实现自定义定义停用方法，并池的 get 或 释放 操作中调用这些方法。

需要Reset的状态取决ON池对Object的指定的行为和组件。ON 释放的常见Reset任务包括停止协程、取消订阅事件、重置 Physics 状态、清除 Animations 和停止粒子系统。释放时停用 ON 游戏对象也很重要，以防止它们在池中处于 Inactive 状态时接收 [`Update`](/engine/6000.0/script-reference/unityengine/monobehaviour/update.md) Calls。

### 示例：汇集飞弹##example:-pooling-projectiles

飞弹`ObjectPool<T>`的典型实现有以下Key阶段：

1. 在游戏Start时创建一个Inactive活动飞弹对象池。向构造函数函数提供所需的委托，以便Whe新建Objectb池ct池ObjectjeObjectOb池ct池ObObjectct池池为回调调用。
2. 当需要飞弹时（例如，当用户发射武器时），使用 `ObjectPool<T>.Get` 从池中获取 Inactive 飞弹。从相应的 `actionOnGet` 回调中，激活检索到的对象，并初始化其位置和方向等任何相关 Properties。
3. 当不再需要飞弹时（例如，当飞弹击中 Target 或超出边界时），用 `ObjectPool<T>.Release` 将其返回到池。通常的做法是为飞弹提供对自身池的引用，以便飞弹可以在DoneWhen释放自己。从相应的 `actionOnRelease` 回调中，停用返回的对象，并重置其速度和 Animation State 等任何相关 Properties。

以下是在`ObjectPool<T>`中集合的飞弹的脚本组件代码。请注意，飞弹有一个public属性性来为其引用自己的池，并在延时一段时间后将其释放池中：

```cs
using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.Pool;
    public class RevisedProjectile :MonoBehaviour
    {
        // Deactivate after delay
        [SerializeField] private float timeoutDelay = 3f;

        private IObjectPool<RevisedProjectile> objectPool;

        // Public property to give the projectile a reference to its ObjectPool
        public IObjectPool<RevisedProjectile> ObjectPool { set => objectPool = value; }

        public void Deactivate()
        {
            StartCoroutine(DeactivateRoutine(timeoutDelay));
        }

        IEnumerator DeactivateRoutine（浮点延时）
        {
            返回 新建 延时;

            // Reset the moving Rigidbody
            Rigidbody rBody = GetComponent<Rigidbody>();
            rBody.linearVelocity = 新建 Vector3(0f, 0f, 0f);
            rBody.angularVelocity = 新建 Vector3(0f, 0f, 0f);

            // Release the projectile back to the pool
            objectPool.Release(this);
        }
    }
```

以下是炮塔所挂的一个组件的代码，该组件发射飞弹并管理飞弹对象的池。当用户射击时，枪会调用对象池上的 `Get` 来获取池中的飞弹：

```cs
using UnityEngine;
    using UnityEngine.Pool;
    using UnityEngine.Events;

    public class RevisedGun :MonoBehaviour
    {
        [工具提示("要射击的预制件")]
        [SerializeField] private RevisedProjectile projectilePrefab;
        [工具提示"Projectile 力")]
        [SerializeField] private float muzzleVelocity = 1500f;
        [工具提示("出现射击的枪支结束点")]
        [SerializeField] private Transform muzzlePosition;
        [工具提示("两次射击之间的时间/较小 = 更高的 Fire Rate")]
        [SerializeField] private float cooldownWindow = 0.1f;

        [SerializeField] private UnityEvent m_GunFired;

        // Stack-based ObjectPool available with Unity 2021 and above
        private IObjectPool<RevisedProjectile> objectPool;

        // Throw an exception if we try to return an existing item, already in the pool
        [SerializeField] private bool collectionCheck = true;

        // Extra options to control the pool capacity and maximum size
        [SerializeField] private int defaultCapacity = 20;
        [SerializeField] private int maxSize = 100;

        private 浮点 nextTimeToShoot;

        private void 唤醒()
        {
            objectPool = 新建 ObjectPool<RevisedProjectile>(CreateProjectile,
                OnGetFromPool, OnReleaseToPool, OnDestroyPooledObject,
                collectionCheck, defaultCapacity, maxSize);
        }

        // Invoked when creating an item to populate the object pool
        private RevisedProjectile CreateProjectile()
        {
            RevisedProjectile projectileInstance = Instantiate(projectilePrefab);
            projectileInstance.ObjectPool = objectPool;
            return projectileInstance;
        }

        // Invoked when returning an item to the object pool
        private void OnReleaseToPool(RevisedProjectile pooledObject)
        {
            pooledObject.gameObject.SetActive(false);
        }

        // Invoked when retrieving the next item from the object pool
        private void OnGetFromPool(RevisedProjectile pooledObject)
        {
            pooledObject.gameObject.SetActive(true);
        }

        // Invoked when the maximum number of pooled items is exceeded (i.e. destroy the pooled object)
        private void OnDestroyPooledObject(RevisedProjectile pooledObject)
        {
            Destroy(pooledObject.gameObject);
        }

        private void FixedUpdate()
        {
            // Invokes the Shoot method if the delay time is exceeded
            if (Input.GetButton("Fire1") && Time.time > nextTimeToShoot && objectPool != null)
            {
                Shoot();
            }
        }

        private void Shoot()
        {
            // Get a pooled object instead of instantiating
            RevisedProjectile bulletObject = objectPool.Get();

            if (bulletObject == null)
                返回;

            // Align to gun barrel/muzzle position
            bulletObject.transform.SetPositionAndRotation(muzzlePosition.position, muzzlePosition.rotation);

            // Move projectile forward
            bulletObject.GetComponent<Rigidbody>().AddForce(bulletObject.变换。正向 * muzzleVelocity, ForceMode.Acceleration);

            // Turn off after a few seconds
            bulletObject.Deactivate();

            // Set cooldown delay
            nextTimeToShoot = Time.time + cooldownWindow;

            m_GunFired.Invoke();
        }
    }
```

使用此代码的完整工作示例 Project，包括 All necessary 预制件和发射池中飞弹的工作炮塔，可从 \[Asset Store（资源商店）]（[https://assetstore.unity.com/packages/essentials/tutorial-projects/level-up-your-code-with-design-patterns-and-solid-289616](https://assetstore.unity.com/packages/essentials/tutorial-projects/level-up-your-code-with-design-patterns-and-solid-289616)）以自由包的形式下载。有关更多信息，请参阅[使用Object Pooling](https://learn.unity.com/course/design-patterns-unity-6/tutorial/use-object-pooling-to-boost-performance-of-c-scripts-in-unity#67a0d722edbc2a14cfcb7400)来提高 C# 脚本在 Unity 中的性能。

### 处理池对象的 Scene 卸载##handling-scene-unload-for-pooled-objects

默认情况下下，对对象池绑定到创建它的Scene。卸载该SceneWhen，Unity 会销毁Scene中的All游戏对象对象，包括池和Any池实例。

通过在调用 [`object.DontDestroyOnLoad`](/engine/6000.0/script-reference/unityengine/object/dontdestroyonload.md) ON 的根游戏对象下放置池管理员，可以使对象池在 Scene 重新加载后持续存在。释放时可以调用 [`transform.SetParent`](/engine/6000.0/script-reference/unityengine/transform/setparent.md) 将池中的父项重新置于池根目录下，以免它们随 Scene 一起销毁。

如果在卸载时 Scene 中可能有活动池实例，请确保它们在 [`OnDisable`](/engine/6000.0/script-reference/unityengine/monobehaviour/ondisable.md) 和 [`OnDestroy` 中](/engine/6000.0/script-reference/unityengine/monobehaviour/ondestroy.md)释放自己，或注册[`SceneManager.activeSceneChanged`](/engine/6000.0/script-reference/unityengine/scenemanagement/scenemanager/activescenechanged.md)回调以调用或销毁项。

避免在InactiveWhen时间引用池实例。使用 [`ObjectPool<T>.Clear`](/engine/6000.0/script-reference/unityengine/pool/objectpool1/clear.md) 可销毁所有 Inactive 实例，例如在关卡之间。

## 池化和重用 Collection 类型##pooling-and-reusing-collection-types

还可以池和重用 [`System.Collection`](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic?view=net-6.0) 命名空间中的 Collection 对象，例如 Lists 和 Dictionaries。

Collection 类公开了 `Clear` 方法，该方法会删除 Collection 的值，但不释放分配给 Collection 的内存。如果要为复杂计算分配临时 helper Collections，这很有用。

以下示例代码每帧分配一次`nearestNeighbors``List`来收集一组数据点，这是一种低效的不良做法：

```lang-cs
// Bad C# script example. This Update method allocates a new `List` every frame.
void Update() {

    列表<float>nearNeighbors = 新建列表<float>();

    findDistancesToNearestNeighbors(nearestNeighbors);

    nearestNeighbors.Sort();

    // … use the sorted list somehow …
}
```

相反，您可以将此`List`从 方法中吊出并放入包含类中，然后每次清除并重用它，这样代码就不需要每帧都分配新建`List`：

```lang-cs
// Good C# script example. This method re-uses the same List every frame.
列表<float> m_NearestNeighbors = 新建列表<float>();

void Update() {

    m_NearestNeighbors.Clear();

    findDistancesToNearestNeighbors(NearestNeighbors);

    m_NearestNeighbors.Sort();

    // … use the sorted list somehow …
}
```

此示例代码在多个帧之间保留和重用`List`实例内存。代码仅在`List`需要 Expand 时分配新建内存。

`UnityEngine.Pool` 命名空间还为多种 Collection 类型（包括 `List<T>`、`HashSet<T>` 和 `Dictionary<TKey, TValue>`）提供现成的池实现。它们的运行原理与 `ObjectPool<T>` 相同，允许根据需要获取和释放 pooled Collection Object 实例。有关更多信息和示例，请参阅同一命名空间下 [`CollectionPool<T>`](ScriptRef:Pool.CollectionPool_1) 和其他 Collection 类型指定的池类的 API 参考文档。

## 其他资源##additional-resources

* [学习教程：使用Object Pooling来提高 Unity 中 C# 脚本的性能](https://learn.unity.com/course/design-patterns-unity-6/tutorial/use-object-pooling-to-boost-performance-of-c-scripts-in-unity#67a0d722edbc2a14cfcb7400)
* [托管内存简介](/engine/6000.0/manual/analysis/performance-memory/managed-memory/introduction.md)
* [参考类型管理](/engine/6000.0/manual/scripting/optimization/performance-optimizing-code-managed-memory/reference-types.md)
* [优化数组](/engine/6000.0/manual/scripting/optimization/performance-optimizing-code-managed-memory/arrays.md)
* [设置飞弹和爆炸](/engine/6000.0/manual/working-with-gameobjects/prefabs/instantiating/projectiles.md)。
