Hello!
Been a while since I’ve posted on here, this seems so simple, and quite frankly I feel like I’m missing something simple.
Below is the FindRandomEnemy() function used by my weapons class. All weapons inherit from this class, but the Sniper and Mortar specifically - for now - use this function to find and attack a random enemy.
I have done about 10 different variations of trying to catch the null, which occurs on line 19.
The enemy controller is on all enemies.
The target is where the bullet aims, where pickups go to, where ui elements appear etc… the transform that acts as the “center” of the enemy.
It sometimes comes back as null. I’d say, <5% of enemies, and only when both weapons are fully upgraded and thus firing very quickly.
I’m 99% sure it’s because by the time it’s called, the enemy is dead and thus destroyed.
But this must happen in between the TryGet and the next line, right?
Any ideas?
It’s uncommon and isn’t game breaking. It has only been found now that my testers are really pushing the edge cases. It’s infuriating that I can’t work this one out!
Thanks
No Kurt, please don’t post your null reference topic!
public virtual void FindRandomEnemy()
{
Collider2D[] hitColliders = Physics2D.OverlapCircleAll(transform.position, DetectionRadius * playerAttributes.Range);
List<Collider2D> enemyColliders = new List<Collider2D>();
foreach (Collider2D hitCollider in hitColliders)
{
if (hitCollider.CompareTag(TagNames.Enemy.ToString()))
{
enemyColliders.Add(hitCollider);
}
}
if (enemyColliders.Count > 0)
{
int randomIndex = UnityEngine.Random.Range(0, enemyColliders.Count);
nearestEnemy = enemyColliders[randomIndex].gameObject;
if(nearestEnemy.TryGetComponent<EnemyController>(out EnemyController controller))
{
target = controller.GetTarget();
if (WeaponName != WeaponNames.MORTAR)
{
Shoot();
}
} else
{
FindRandomEnemy();
}
}
}