Files
AnnoyingUtils/Pool/README.md
2024-07-10 17:20:34 +08:00

43 lines
1.2 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
新建一个对象池类继承`SingletonObjectPool<T>`在UnityEditor中会自动创建以类名为名称的单例实例。
```csharp
public class EnemyPool : SingletonObjectPool<Enemy>
{
}
```
用法示例如下方刷怪圈
```csharp
public class EnemySpawner : MonoBehaviour
{
public GameObject enemyPrefab;
public int initialPoolSize = 5;
public int maxPoolSize = 10;
public float spawnInterval = 3f;
public int spawnCount = 1;
public float spawnRadius = 5f;
private void Start()
{
SingletonObjectPool<Enemy>.Instance.Init(enemyPrefab.GetComponent<Enemy>(), initialPoolSize, maxPoolSize);
StartCoroutine(SpawnEnemiesCoroutine());
}
private IEnumerator SpawnEnemiesCoroutine()
{
while (true)
{
yield return new WaitForSeconds(spawnInterval);
SpawnEnemies();
}
}
private void SpawnEnemies()
{
for (var i = 0; i < spawnCount; i++)
{
var spawnPosition = transform.position + (Vector3)Random.insideUnitCircle * spawnRadius;
SingletonObjectPool<Enemy>.Instance.Spawn(transform).transform.position = spawnPosition;
}
}
}
```