# Preventing a game object that has faded out from colliding with other game objects

I have the following cycle for fading sprites in and out

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

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;
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;
}

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?

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

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..

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