Problem with keeping on track with targets in a list

Hello, we are creating a tower defense game and have a problem with creating persistent list of targets for turrets.

So basicly I am detecting the enemy with collison and add them to a list to keep on track about enemies in my range, also I subscribe to the enemy onKilled event.
I use another list which is a subset of the _targetsInRange these are all the enemies I have a line of sight on.

If the enemy dies I Remove it from both lists, then unsubscribe from the event and reset the target to null and look for another target.

The problem is that sometimes the enemy deletes itself but not from my list. As a result my target lists are full with missing values. How can I avoid this happening?

Also this error only occures occasionally. Sometimes it happens and breaks everything sometimes it works normally. However this problem is more usual if the enemies get damage from other sources like status effects or player damage.

How can I make sure that dead enemies get removed from both target list?

    public class TowerShooting : MonoBehaviour
    {
        private Transform _head;

        private Transform _bulletOrigin; 

        [SerializeField] private List<EnemyController> _targetsInRange = new List<EnemyController>();
        [SerializeField] private List<EnemyController> _targetsInSight = new List<EnemyController>();
        [SerializeField] private LayerMask _hitLayer;
        [SerializeField] private LayerMask _enemyLayer;
        [SerializeField] private Transform _target = null;
        private bool _canShoot = false;



        public void AddTargetToInRange(EnemyController target)
        {
            _targetsInRange.Add(target);
            target.OnEnemyKilled += HandleOnEnemyKilled;
            EnsureSight();
        }

        public void RemoveTargetFromInRange(EnemyController target)
        {
            _targetsInRange.Remove(target);
            if (_targetsInSight.Contains(target))
            {
                _targetsInSight.Remove(target);
            }

            target.OnEnemyKilled -= HandleOnEnemyKilled;
            _target = null;

            EnsureSight();
        }

        private void EnsureSight()
        {
            if (_targetsInRange.Count > 0)
            {
                foreach (EnemyController target in _targetsInRange)
                {
                    var direction =  target.transform.position - _origin;
                    Debug.DrawRay(_origin, direction);
                    Ray ray = new Ray(_origin, direction);

                    if (Physics.Raycast(ray, out RaycastHit hit, 1000f, _hitLayer))
                    {                                             
                        if (((_enemyLayer.value & (1 << hit.collider.gameObject.layer)) > 0) && (!_targetsInSight.Contains(target)))
                        {
                            _targetsInSight.Add(target);
                        }
                        else if ((_enemyLayer.value & (1 << hit.collider.gameObject.layer)) <= 0 &&        _targetsInSight.Contains(target))   
                        {
                            _targetsInSight.Remove(target);
                        }
                    }
                }
              
              
               GetTarget();
            }
            else
            {
                _target = null;
            }
        }

        private void GetTarget()
        {
            if (_targetsInSight.Count > 0)
            {
                switch (_targetingStyle)
                {
                    case TowerEnums.TargetingStyle.First:
                        _target = GetEnemyPosition.First(_targetsInSight);
                        break;
                    case TowerEnums.TargetingStyle.Last:
                        _target = GetEnemyPosition.Last(_targetsInSight);
                        break;
                    case TowerEnums.TargetingStyle.Strongest:
                        _target = GetEnemyPosition.Strongest(_targetsInSight);
                        break;
                    case TowerEnums.TargetingStyle.Weakest:
                        _target = GetEnemyPosition.Weakest(_targetsInSight);
                        break;
                    case TowerEnums.TargetingStyle.Closest:
                        _target = GetEnemyPosition.Closest(_targetsInSight, transform.position);
                        break;
                    default:
                        _target = GetEnemyPosition.First(_targetsInSight);
                        break;
                }
            }
        }

        private void HandleOnEnemyKilled(EnemyProperties enemy)
        {
            EnemyController enemyScript = _target.GetComponent<EnemyController>();

            RemoveTargetFromInRange(enemyScript);
        }

        private void Update()
        {
            if (_target != null)
            {
                _canShoot = true;
            }
            else
            {
                _canShoot = false;
            }
            TargetEnemy();
            _towerController.Shoot(_canShoot);

            if(_targetsInRange.Count > 0)
            {
                EnsureSight();
            }


        }


        private void TargetEnemy()
        {
            //Targeting and shooting
        }
    }

By identifying how the enemy is deleting itself and not updating the bookkeeping!

The most common way to do this is to create a method that does both things, then audit your code to ensure nothing does either the bookkeeping or the destroying, and that it always calls your combined method.

If you have no idea where this might go, it is time to start debugging! Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.