stop coroutine at specific event completion.

hello guys,
i am using following code to fade an object.its working fine but once object fade and if i bring other object again on faded object the faded object appers again and then fade again.i need once object fades its not appear again.Please help.

using UnityEngine;
using System.Collections;

public class DustFade : MonoBehaviour {

//Usethisforinitialization
void OnTriggerEnter2D (Collider2Dother){

if(other.tag =="Towel")
{

Start Coroutine(Fade());

}

}

IEnumerator Fade() {
for (floatf = 1f; f >= 0; f -= 0.1f) {
Colorc = renderer.material.color;
c.a = f;
renderer.material.color = c;
yield return new WaitForSeconds(0.30f);
}
}
}

I would be doing this differently:

public bool fade;

[Range(1f, 10f)]
public float fadeSpeed;

static Color faded = new Color(1f, 1f, 1f, 0f);

void Update() {

   var targetColor = (fade) ? Color.white : faded;

   renderer.material.color = Color.Lerp(renderer.material.color, targetColor, Time.deltaTime * fadeSpeed);

}

void OnTriggerEnter2D(Collider2D other) {

    if (other.tag == "Towel")
        fade = true;

}

Dude it isnt working.its executing no errors but it does nothing.plesse check it and reply.

Did you set fade speed in the editor?

i give fadespeed.now script running but object faded/dispersed at once even i didnt touch the towel.i want it on towel collissin .plz reply.

IEnumerator Fade() {
    Color c = renderer.material.color;

    for(int i=0;i<10;i++){
        c.a -= 0.1f;
        renderer.material.color = c;
        yield return 0;
    }
}
1 Like

You don’t seem to be putting much effort into this. It’s important that you learn how the code works and do some error-checking/exploration on your own.

It doesn’t do you much good as a developer if you come onto the forums and expect the users here to do all your work for you.

Make sure that ‘fade’ is UNCHECKED in the editor before you press play.

Thanks ,it works fine. I added yield return newWait ForSeconds(0.20f);
it give me my desired results :slight_smile: