Problems with if/else [Like, totally fixed]

Started by Lewis, Thu 01/12/2011 14:48:03

Previous topic - Next topic

Lewis

Hello!

I'm having some problems with the if/else commands.

The situation is this.

The player has several inventory items at this point in the game. Most of the inventory items need to just bring up a "that won't work" kinda display. One of them is *almost* right, and needs to bring up a display saying as such. And then another one is the right one, which should initiate a dialogue.

The problem is that, when you use the correct inventory item, it displays the 'else' text *before* going on to initiate the conversation. In other words, the dialogue initiation works correctly, but it displays text beforehand that should only be displayed if another inventory item is used.

I'm probably missing something mega stupid with this, so apologies in advance.

Here's the code:

function cHomeless_UseInv()
{
 if (cJack.ActiveInventory == iTwenty1)
{dHomeless2.Start();
 cJack.AddInventory(iDirtyShoes1);}
 if (cJack.ActiveInventory == iMoney1)
{Display("I *really* can't dip into Mike's money for a homeless person, as much as I'd like to help."); }
 else Display("I don't think he'd appreciate that.");
}
Returning to AGS after a hiatus. Co-director of Richard & Alice and The Charnel House Trilogy.

Khris

The reason is twofold:

1) The else ignores the outcome of the first if test; just replace the second "if" with "else if" and you're set.
To deal with several possible conditions, you have to use "if ... else if ... else if ... [...] ... else".

2) The reason for the else code being executed before the dialog: dialogs aren't started until the current function has finished. So if you wanted to run code after a dialog, put it inside the dialog script.

Btw, you have a really confusing way of structuring your code, here's how I do it:
Code: ags
function cHomeless_UseInv() {

  if (cJack.ActiveInventory == iTwenty1) {
    dHomeless2.Start();
    cJack.AddInventory(iDirtyShoes1);
  }
  else if (cJack.ActiveInventory == iMoney1)
    Display("I *really* can't dip into Mike's money for a homeless person, as much as I'd like to help.");
  else
    Display("I don't think he'd appreciate that.");
}

Lewis

Bingo! Thanks so much. Yeah, my code mainly got messy from trying various {} in various places. All tidy now.

Thanks once again! :-)
Returning to AGS after a hiatus. Co-director of Richard & Alice and The Charnel House Trilogy.

SMF spam blocked by CleanTalk