I think my understanding of how if statements function is incorrect. The code attached below may highlight my misconception.
I thought that if a condition was true, then the program will run through the if block until the condition is no longer true. At that point, it will move down the block and see if the next if statement is true. If this is not true, it will go back to the beginning again if the main if statement is still true. At this point, a new bool value will be assigned based on the method Initiative() and the code will move down again.
With the code, I am trying to create a very basic combat initiative system. If the player gets a higher initiative roll, then player attacks. If not, player blocks. The attacking and blocking should last for as long as the attackTimer is > than 0. The problem is that the player just stands there and jitters as the code rapidly alternates between true and false.
I suspect the problem has something to do with where I put the bool “value” but I’m not sure how to fix it. It’s as if the program doesn’t just move politely down the block once value has been initialized, but jumps up again constantly to see if value has changed and, since value is established randomly, when the program goes to see if value has changed, it has!
private void AttackEnemy()
{
if(Vector3.Distance(playerTransform.position, enemyTarget.transform.position) < attackRange)
{
bool value = Initiative();
attackTimer = 21;
attacking = true;
if(value == true && attacking == true)
{
Debug.Log(value + " Should be true");
animation.Play(attack.name);
while (attackTimer > 0 && attacking == true)
{
attackTimer -= Time.deltaTime;
if(attackTimer < 0)
{
attackTimer = 0;
}
if(attackTimer == 0)
{
enemyVitals.AdjustCurrentBeastHealth(-damage);
attacking = false;
}
}
}
else if(value == false && attacking == true)
{
Debug.Log(value + " Should be false");
animation.Play(playerBlock.name);
while (attackTimer > 0 && attacking == true)
{
attackTimer -= Time.deltaTime;
if(attackTimer < 0)
{
attackTimer = 0;
}
if(attackTimer == 0)
{
enemyVitals.AdjustCurrentBeastHealth(0);
attacking = false;
}
}
}
}
}
public bool Initiative()
{
int playerRoll = Random.Range(1,20);
int enemyRoll = Random.Range(1,20);
if(playerRoll > enemyRoll)
{
return true;
}
else
{
return false;
}
}