Can't understand how to use yield

In my FPS when I kill boss I want to play bossDyingMusic and then destroy boss game object. I need to use yield, because else music don’t have time to be played.

But when I use yield, I’m getting an error:
The body of HealthBoss.Update()' cannot be an iterator block because void’ is not an iterator interface type

void Update ()
{
	if (healthMonster <= 0)
	{
		boss.audio.Play();
		yield return WaitForSeconds(5);
		Destroy (boss);
	}
}

In C#, you can only use yield keyword in methods of type IEnumerator. So you’ll have to create an IEnumerator method. And this if statement of yours wouldn’t work as intended because Update gets called every frame so it’ll keep playing that music over and over again while throwing a null reference exception since you try to destroy something you just destroyed in previous frame.

What you can do, instead, is create an enemy script and declare a health variable. Everytime the health decreases, check if it’s 0 or smaller than 0 to determine whether your enemy is still alive or not, just like you tried to do in that Update method. If dead, you can call a method of type IEnumerator to play music then destroy the boss which would look like this :

IEnumerator PlayThenKill()
{
    boss.audio.Play();
    yield return new WaitForSeconds(5);
    Destroy(boss)
}

Don’t forget to call PlayThenKill using StartCoroutine method :

StartCoroutine(PlayThenKill());

This is because Update is not a coroutine. yield only works in functions started with StartCoroutine(). StartCoroutine will only work with functions that return IEnumerator.

To fix your problem make a new coroutine:

public IEnumerator killBoss()
{
boss.audio.Play();
yield return WaitForSeconds(5);
Destroy(boss);
yield break;
}

Then do:
if (healthMonster <= 0)
{
StartCoroutine(“killBoss”);
}

Must be IEnumerable as the return type since it’s an iterator

IEnumerable Update ()
{
    if (healthMonster <= 0)
    {
        boss.audio.Play();
        yield return new WaitForSeconds(5);
        Destroy (boss);
    }
}

Have you looked up how to use Coroutines ? This is basically what you’re trying to achieve here.

I don’t believe you can turn Update into a coroutine though. What you’re gonna need to do is make another function and start it in the update. here’s what i’m thinking :

void Update()
{
    if (healthMonster <= 0)
    {
        StartCoroutine("MyFunction");
    }

}

IEnumerator MyFunction()
{
    boss.audio.Play();
    yield return WaitForSeconds(5);
    Destroy (boss);
}