- Home /
Increment based 'if' conditions not being met for the later conditions. Any solutions ?
I'm trying to show SpriteA if ObjectA collided with 4 enemies and SpriteB if ObjectA collided with 6 enemies. The 'if' condition for SpriteA is met first in any scenario. If my ObjectA really collides with 6 enemies, as soon as the counter reaches 4 enemies, SpriteA is shown and the other 2 enemies are disregarded and not taken into account and hence SpriteB is never shown. How can I achieve this behavior ? An example script as shown below:
public List<GameObject> collidedEnemies;
if (collidedEnemies.Count == 4)
{congratulatoryGameObject.GetComponent<SpriteRenderer> ().sprite = SpriteA;
}
if (collidedEnemies.Count == 6)
{congratulatoryGameObject.GetComponent<SpriteRenderer> ().sprite = SpriteB;
}
What deter$$anonymous$$es the contents of collidedEnemies
? If these are colliders, then I'm guessing after 6 enemies triggers, it very quickly triggers with 4 again, so you don't see the sprite. You can probably check if that's what's happening with:
public List<GameObject> collidedEnemies;
private bool had6 = false;
if (collidedEnemies.Count == 4 && !had6)
{
congratulatoryGameObject.GetComponent<SpriteRenderer> ().sprite = SpriteA;
}
if (collidedEnemies.Count == 6)
{
congratulatoryGameObject.GetComponent<SpriteRenderer> ().sprite = SpriteB;
had6 = true;
}
This code should work, I assume the problem is somewhere else. Consider running a Debug.Log(collidedEnimies.Count) to see if it ever actually reaches 6.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
How to achieve 2D pixel perfect collision physics (like Badland) in Unity3D ? 3 Answers
Can't change variables on collision, if statement being ignored 1 Answer
Collisions and Lists 1 Answer
how do i keep a sprite on a plane from flipping around when colliding? 3 Answers