save
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
using Godot;
|
||||
using System.Collections.Generic;
|
||||
|
||||
public enum EnemyType
|
||||
{
|
||||
Stone,
|
||||
Stump,
|
||||
Liquid
|
||||
}
|
||||
|
||||
public partial class EnemyPool : Node
|
||||
{
|
||||
[Export] private Godot.Collections.Dictionary<EnemyType, PackedScene> _scenes;
|
||||
[Export] private int _poolSize = 10;
|
||||
|
||||
private readonly Dictionary<EnemyType, Queue<Enemy>> _pool = new();
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
foreach (var kvp in _scenes)
|
||||
{
|
||||
var q = new Queue<Enemy>();
|
||||
_pool[kvp.Key] = q;
|
||||
|
||||
for (int i = 0; i < _poolSize; i++)
|
||||
q.Enqueue(CreateEnemy(kvp.Key));
|
||||
}
|
||||
}
|
||||
|
||||
private Enemy CreateEnemy(EnemyType type)
|
||||
{
|
||||
var e = _scenes[type].Instantiate<Enemy>();
|
||||
e.Died += ReturnToPool;
|
||||
return e;
|
||||
}
|
||||
|
||||
public Enemy Get(EnemyType type)
|
||||
{
|
||||
if (!_pool.TryGetValue(type, out var q))
|
||||
return null;
|
||||
|
||||
var e = q.Count > 0 ? q.Dequeue() : CreateEnemy(type);
|
||||
e.ResetEnemy();
|
||||
return e;
|
||||
}
|
||||
|
||||
private void ReturnToPool(Enemy e)
|
||||
{
|
||||
e.GetParent()?.RemoveChild(e);
|
||||
e.ProcessMode = ProcessModeEnum.Disabled;
|
||||
_pool[e.Type].Enqueue(e);
|
||||
}
|
||||
|
||||
public EnemyType GetRandomType()
|
||||
{
|
||||
var keys = new List<EnemyType>(_pool.Keys);
|
||||
return keys[GD.RandRange(0, keys.Count - 1)];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user