Why isn't my simple if statement working?

if(Vector3.Distance(transform.position, Player.PlayerPosition) <= AggroRange && AggroTrigger == true){

transform.LookAt(Player.PlayerPosition);
if( Vector3.Distance(transform.position, Player.PlayerPosition) > MinRange ){
transform.Translate (Vector3.forward * EnemySpeed * Time.deltaTime);
}
if(CanAttack == true && AggroTrigger==true)
{
AggroTimer = 20;
Player.PlayerHealth -= 20;
CanAttack = false;
AttackSpeed = 0;
}
}
So I am obviously telling Unity: if the distance betweeen the player and enemy is smaller than or equals to 50, and AggroTrigger is true, execute the code, the problem is even when AggroTrigger is false it executes it, I have no clue where I might be wrong since if statements should be the simplest thing, Unity is just not listening to me, maybe it’s a bug, maybe I’m stupid, but I just want to fix this annoying problem.

AggroTrigger becomes true when AggroTimer is between 1 and 20, false if it’s 0 or above 20.

Just a thought:
If these things (the code above and the AggroTimer stuff) happen simultaneously, AggroTrigger could technically become false right after checking that it is true.

Otherwise I would advise to just use Debug.Log() and do some investigating :slight_smile:

1 Like

Yeah, the if statement looks fine, and it’s not going to arbitrarily decide to ignore some part of the statement and trigger the block inside anyways. That means that AggroTrigger is true when it triggers, and you’ll need to either post a much larger section of your code (in [code ][/code ] tags, please) or place some Debug.Logs around and try to narrow down exactly where the mistake is occurring on your own. I highly recommend the latter option, because that’s how debugging works.

If you look up breakpoints, you can also check it out that way too (possibly far easier).