NullReference in Play mode

So, I am working on a RTS game, and my code for enemy detection throws a NullReferenceExeption when I enter Play mode. Here is the code:

Dictionary<float, Transform> enemys = new Dictionary<float, Transform>();

Collider[ ] enemiesSighted;
List distances;

float highestDist;

enemiesSighted = Physics.OverlapSphere(transform.position, sightRange, enemy);

if (enemiesSighted != null)
{
for (int i = 0; i < enemiesSighted.Length; i++)
{
float dist = Vector3.Distance(transform.position, enemiesSighted*.transform.position);*
distances.Add(dist);
enemys.Add(dist, enemiesSighted*.transform);*
}
for (int i = 0; i < distances.Count; i++)
{
if (enemys.ContainsKey(distances*))*
{
if (distances > highestDist)
{
highestDist = distances*;*
}
}
}
if (enemys.ContainsKey(highestDist))
{
enemys.TryGetValue(highestDist, out enemyToAttack);
Debug.Log(enemyToAttack);
//Attack(enemyToAttack.gameObject);
}
If someone could help me with this, that would be great.

War. War never changes.

Neither does NullReferenceException. NullReferenceException never changes.

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Steps to success:

  • Identify what is null
  • Identify why it is null
  • Fix that

If you actually have a forum question in the future, if you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: Using code tags properly