2
\$\begingroup\$

I have the following cycle for fading sprites in and out

fade out (1 second) -> delay (2 seconds)-> fade in -> delay (2 seconds)

Please see my code below:

IEnumerator FadeTo(Material material, float targetOpacity, float duration) {

    Color color = material.color;
    float startOpacity = color.a;

    float t = 0;

    while(t < duration) {
        t += Time.deltaTime;
        float blend = Mathf.Clamp01(t / duration);

        color.a = Mathf.Lerp(startOpacity, targetOpacity, blend);
        material.color = color;
        yield return null;
    }
}    


IEnumerator EnemyCycle()
{

    while (isRepeating)
    {

        for (int j = 0; j < enemies.Length; j++) {

            var _myMaterial = enemies [j].GetComponent<Renderer>().material;
            var _currentFade = StartCoroutine(FadeTo(_myMaterial, 0f, 1f));
            enemies [j].GetComponent<CircleCollider2D> ().enabled = false;
        }

        yield return new WaitForSeconds (2);

        for (int j = 0; j < enemies.Length; j++) {

            enemies [j].GetComponent<CircleCollider2D> ().enabled = true;
            var _myMaterial = enemies [j].GetComponent<Renderer>().material;
            var _currentFade = StartCoroutine(FadeTo(_myMaterial, 1f, 1f));
        }

        yield return new WaitForSeconds (2);

    }
}

The above code cycle works when I am not disabling and enabling the colliders. i.e., without the following lines of code:

enemies [j].GetComponent<CircleCollider2D> ().enabled = false;
enemies [j].GetComponent<CircleCollider2D> ().enabled = true;

But when I place the two lines (as I've done in the above code), the enemy game objects don't follow the fade in and out cycle, mostly they don't even fade out. I really need to be able to prevent the enemies from colliding with other game objects when I have faded them out during my fade in and out cycle. How can I solve this issue?

\$\endgroup\$
1
  • \$\begingroup\$ I am still trying to figure this out. Would really appreciate some help. \$\endgroup\$ – Bane Jun 23 '17 at 4:05
1
\$\begingroup\$

I just tested your code, it's working here for me. A few things

  • Maybe there is another object interacting with this behaviour?

  • Did you set the colliders?

  • Are you getting any errors?

  • There's a plats [j].GetComponent ().enabled = true;

  • Also, how did u define the isRepeating variable? Is the value set to true?

  • did you mean 'enemies' instead of plats ?

    Sorry, i cannot comment, i dont have 50 reputation..

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I was setting a CircleCollider instead of a BoxCollider. Thanks \$\endgroup\$ – Bane Jun 23 '17 at 5:04
  • 1
    \$\begingroup\$ Now you got the reputation to comment :D. \$\endgroup\$ – Aditya Yadav Jun 23 '17 at 5:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.