Home > Back-end >  Is it better practice to keep a static list of every game object as they are instantiated, or to use
Is it better practice to keep a static list of every game object as they are instantiated, or to use

Time:11-16

If I want to check for the closest gameObject with the class "Enemy", I have two options:

  1. I can build a static list of every Enemy gameObject that is instantiated, and find the closest one using the list, or
  2. I can use physics raycasts to find every Enemy gameObject, put them into a list, and find the closest one like that.

They both seem about equal; if anything, it seems like building a static list would have better performance since there's no raycasting involved, but on the other hand using approach 2 seems like it is more extensible for further changes.

CodePudding user response:

This sounds quite opinion based but here is what I would do

public class Enemy : MonoBehaviour
{
    private static readonly List<Enemy> _instances = new ();
    public static IReadOnlyList<Enemy> Instances => _instances;

    private void Awake()
    {
        _instances.Add(this);
    }

    private void OnDestroy()
    {
        _instances.Remove(this);
    }
}

This way you always have the actual list of existing instances without needing to poll them all the time.

Now you can get the closest one e.g. using Linq

var closestEnemy = Enemy.Instances.OrderBy(e => (e.transform.position - transform.position).sqrMagnitude).FirstOrDefault();

Using physics is no good approach if you need to find all the Enemy instances anyway.


Depends on your use case though. You might only want to get those within a certain range. In that case you could again either use above approach and filter on a specific distance or you could use e.g. an OverlapSphere. Performance wise I claim that Physics will always be worse.

  • Related