Game Development Community

If statement not correctly checking variable

by Laralyn McWilliams · in Torque Game Builder · 04/05/2010 (4:10 pm) · 2 replies

I'm sure it's a simple mistake... but I'm having trouble spotting it. Here are the relevant code bits:

function InitBattle()
{
   //coin toss to see who goes first
   %coinToss = getRandom(1,2); 
   if (%coinToss > 1)
   {
      $battleTurn = "player";
   }
   else
   {
      $battleTurn = "enemy";
   }
   
   //show turn in placeholder field
   turnText.text = $battleTurn;
   
   //hand off to function for whoever won the coin toss
   if ($battleTurn == "player")
   {
      ProcessPlayerAttack();
   }
   else
   {
      ProcessEnemyAttack();
   }
}

function playerAttackButton::onClick(%this)  
   {  
         if ($battleTurn == "player")
         {
            $enemy1.currentHealth = ($enemy1.currentHealth - $player1.baseAttack);
            EnemyHealth.text = $enemy1.currentHealth;
         }
   }

When I debug, the if statement in playerAttackButton processes the statement even if $battleTurn is not equal to "player." Here's a screen shot showing the code currently past the if statement when the Watch shows the variable is set to "enemy." eluminarts.com/images/tgb/tgb1.jpg

What am I doing wrong? Thanks!

#1
04/05/2010 (4:19 pm)
== is for comparing numeric values, and both "player" and "enemy" are 0 when converted to a number.

To compare strings, you need to use $= (equals) and !$= (not equals).
#2
04/05/2010 (4:37 pm)
Ah ha! See, I knew it was something simple. :-)

Thanks for the quick response. I really appreciate it!