Problem using lerp and material alpha to fade out a gameObject when enemy is killed

Hi, I am trying to make the object fade out when its killed, however all it does is just disappear when the destroy is called. Please can someone figure out where I have gone wrong trying to lerp the alpha channel, I thought I had done this correctly!

I cant see the wood for the trees anymore :wink:

   void Dead()
    {
        if (audio.isPlaying) return;
        audio.PlayOneShot(enemyDeathSounds[Random.Range(0, enemyDeathSounds.Length)]);
        enemyAlive = false;
        anim.enabled = false;
        movement.enabled = false;
        hearing.SetActive(false);
        sight.SetActive(false);
        melee.SetActive(false);
        nav.enabled = false;
        StartCoroutine(DestroyCorpse());
    }

    IEnumerator DestroyCorpse()
    {
            yield return new WaitForSeconds(corpseFadeDelay);
            StartCoroutine(FadeTo(1.0f, 2.0f));
            Destroy(this.gameObject);    
    }

    IEnumerator FadeTo(float fadeValue, float aTime)
    {
        float alpha = model.renderer.material.color.a;
        for(float t = 0.0f; t < 1.0f; t +=Time.deltaTime / aTime)
        {
            Color newColor = new Color(1, 1, 1, Mathf.Lerp(alpha,fadeValue, t));
            model.renderer.material.color = newColor;
            yield return null;
        }
        
    }

Any help would be greatly appreciated :slight_smile: Oh and if my code is badly written, bear with me I am still learning!

It’s pretty clear what’s happening. You start off the coroutine that fades out the material, and then immediately destroy the object:

StartCoroutine(FadeTo(1.0f, 2.0f)); //This starts to fade out the object
Destroy(this.gameObject); //This destroys the object immediately

What you probably want to do is to move your Destroy-call to the end of the FadeTo method. If the fadeDelay is supposed to be a wait between when fading starts and when the destroy is called, you just need to reorder your DestroyCorpse Coroutine to this:

StartCoroutine(FadeTo(1.0f, 2.0f));
yield return new WaitForSeconds(corpseFadeDelay);
Destroy(this.gameObject);

The Destroy function is not part of the CoRoutine which means that it will be called immediately after you call start the Coroutine and the object will be destroyed at the end of the first frame. The easiest solution is to include the fadetime as the delay parameter in the destroy function:

Destroy(gameObject, 2.0f);

At line 18 you are calling FadeTo(1.0f, 2.0f), where the first parameter is the fade value and you have set it to 1.0f. This means that the FadeTo function will fade the alpha to 1.0f which is fully opaque. You probably want to use 0.0f for the fade value so it fades to fully transparent instead.