Skip to content

Instantly share code, notes, and snippets.

@RoeiRubach
Created April 19, 2020 21:58
Show Gist options
  • Select an option

  • Save RoeiRubach/32b3a562bdd3b335a343e482205ed3ce to your computer and use it in GitHub Desktop.

Select an option

Save RoeiRubach/32b3a562bdd3b335a343e482205ed3ce to your computer and use it in GitHub Desktop.
[Enemy Pool Controller] a collection for accessing any that currently exist. I do this frequently with what I call a 'MultitonPool'.
using UnityEngine;
using System.Collections.Generic;
public class EnemyPoolController : MonoBehaviour
{
public readonly static HashSet<EnemyPoolController> Pool = new HashSet<EnemyPoolController>();
private void OnEnable()
{
EnemyPoolController.Pool.Add(this);
}
private void OnDisable()
{
EnemyPoolController.Pool.Remove(this);
}
public static EnemyPoolController FindClosestEnemy(Vector3 characterPos)
{
EnemyPoolController result = null;
float distance = float.PositiveInfinity;
var enumerator = EnemyPoolController.Pool.GetEnumerator();
while (enumerator.MoveNext())
{
float currentDistanceToCharacter = (enumerator.Current.transform.position - characterPos).sqrMagnitude;
if (currentDistanceToCharacter < distance)
{
result = enumerator.Current;
distance = currentDistanceToCharacter;
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment