script+c__Iterator1.MoveNext() nullreference exception error

So i’ve made this bomb script which consists of one IEnumerator with a raycast array inside of it, and there’s two yield return new waitforseconds inside aswell. The bomb works this way, u place the bomb, it waits for 2.5 seconds, then iterates through the loop and destroys everything with the layer whatIsDestroyable.

Everything actually works fine, but i just get a nullreference error once the bomb sets off, ie at hit*.transform.SendMessage("DamageTaken", damage, SendmessageOptions.DontRequireReciever); the error is Grenade2+c__Iterator1.MoveNext() at cs 30*
idk if it makes sense, but i think the error comes from theres nothing to iterate through or something? what can i do to solve this? should i use a list? anyways heres the code:
public Transform pointOfCircle;

  • public float radius = 0.5f;*

  • public LayerMask whatIsDestroyable;*

  • public float distance = 1f;*

  • public int damage = 1;*

  • public float waitTime = 1f;*

  • public float timeToDestroy = 0.2f;*

  • void Update()*

  • {*

  •  StartCoroutine ("Bomb");*
    
  • }*

  • private IEnumerator Bomb()*

  • {*

  •  RaycastHit2D[] hit;*
    
  •  hit = Physics2D.CircleCastAll (pointOfCircle.position, radius, new Vector2 (1, 1), 0.5f, whatIsDestroyable);*
    
  •  for (int i = 0; i < hit.Length; i++)* 
    
  •  {*
    
  •  	yield return new WaitForSeconds(waitTime);*
    

_ hit*.transform.SendMessage(“DamageTaken”, damage, SendMessageOptions.DontRequireReceiver);_
_
yield return new WaitForSeconds(timeToDestroy);_
_
Destroy (gameObject);_
_
}*_

* }*

You have several issues here. First of all you start a new coroutine every frame since you have your StartCoroutien in Update. Second you seem to yield at a pretty strange point in your coroutine. If your bomb should have a delay before it goes off you should just have a single yield at the beginning before you actually do your CircleCastAll. That way you have the most recent objects available when the bomb actually goes off and not those objects that where in range when you dropped it.

Another issue is that you destroy the bomb object inside your loop at the end. This makes no sense since destroying the gameobject will terminate the coroutine as well. So the loop can never do a second iteration.

So it should be look something like this:

void Start()
{
    StartCoroutine(Bomb());
}

private IEnumerator Bomb()
{
    yield return new WaitForSeconds(waitTime);
    RaycastHit2D[] hit;
    hit = Physics2D.CircleCastAll (pointOfCircle.position, radius, new Vector2 (1, 1), 0.5f, whatIsDestroyable);
    for (int i = 0; i < hit.Length; i++) 
    {
        if (hit*.transform != null)*

{
hit*.transform.SendMessage(“DamageTaken”, damage, SendMessageOptions.DontRequireReceiver);*
yield return new WaitForSeconds(timeToDestroy);
}
}
Destroy (gameObject);
}