After the WaitForSeconds Function, My Code Doesn't Continue

Hello! My grenade script works fine but the object would destroy itself before the sound played, so I added a “yield return new WaitForSeconds()” but when the script waits the seconds I put in,
the code doesn’t continue. the grenade is not getting destroyed by script. Any advice?

Code:

using System.Collections;
using UnityEngine;

public class Grenade : MonoBehaviour
{
public float delay = 5f;
public float radius = 5f;
public float force = 1000f;
public float damage = 750f;
public float grenadeAmount = 3f;

public GameObject explosionEffect;
public AudioSource esfx;
float countdown;
bool hasExploded = false;

// Start is called before the first frame update
void Start()
{
countdown = delay;
}

// Update is called once per frame
void Update()
{
countdown -= Time.deltaTime;
if (countdown <= 0f && !hasExploded)
{
Explode();
hasExploded = true;
}
}

void Explode()
{
esfx.Play();
GameObject EFX = Instantiate(explosionEffect, transform.position, transform.rotation);
Destroy(EFX, 3f);
Collider[ ] collidersToDestroy = Physics.OverlapSphere(transform.position, radius);
foreach (Collider nearbyObject in collidersToDestroy)
{

Target dest = nearbyObject.GetComponent();
if (dest != null)
{
dest.Die();
}
}
foreach (Collider nearbyObject in collidersToDestroy)
{
Ragdoll dest = nearbyObject.GetComponent();
if (dest != null)
{
dest.Die();
}
}

Collider[ ] collidersToMove = Physics.OverlapSphere(transform.position, radius);
foreach (Collider nearbyObject in collidersToMove)
{
Rigidbody rb = nearbyObject.GetComponent();
if (rb != null)
{
rb.AddExplosionForce(force, transform.position, radius);
EndPart();
}
}

IEnumerator EndPart()
{
yield return new WaitForSeconds(3);
Destroy(gameObject); // does not do this code!
}
}
}

Coroutines cannot be called like regular methods; you need to use StartCoroutine().

StartCoroutine(EndPart());
1 Like

Thanks! do I put it in the Start method?

Nevermind, I put the StartCoroutine(EndPart()); after i called the EndPart method. Thanks for your help!