Adventure Game Studio

AGS Support => Beginners' Technical Questions => Topic started by: mattixz0421 on Sat 14/12/2019 22:16:13

Title: A Little Confused With Scripting
Post by: mattixz0421 on Sat 14/12/2019 22:16:13
I'm trying to script so that when I use an inventory on a character I get a new inventory item and lose one. And then if you click the new item on it you get a new message, but for some reason all inventory items do the same action.

This is what I have in the script. I'm new to scripting and I'm sure I made a minor mistake.

function cFruit_UseInv()
{
if(player.ActiveInventory == iemptycup)
cEgo.Walk(149, 146, eBlock);
Display("Roger waves the empty cup under the giggling red fruit, eventually enough fruit juice spills into the cup. It almost looks like human blood.");
cEgo.AddInventory(icupofblood);
cEgo.LoseInventory(iemptycup);

if(player.ActiveInventory == icupofblood)
cEgo.Walk(149, 146, eBlock);
Display("You have plenty of fruit juice.");


}
Title: Re: A Little Confused With Scripting
Post by: mattixz0421 on Sat 14/12/2019 22:22:25
Nevermind I actually solved the problem on my own.
Title: Re: A Little Confused With Scripting
Post by: Snarky on Sat 14/12/2019 22:25:39
An "if", by default, only applies to the next line. If you want it to apply to a whole bunch of lines, you have to put them inside curly brackets, {}. That makes what's called a "block". Because you haven't done that, whenever you use the Fruit, it only checks the "if" conditions for the following cEgo.Walk() lines. The others are executed regardless.

It is conventional to indent the line or block of lines that the "if" applies to by a tab, to clearly show the scope of the condition. (The same thing is also done for functions, loops and other program structures.)

So your code should look like this:

Code (ags) Select
function cFruit_UseInv()
{
  if(player.ActiveInventory == iemptycup)
  {
    cEgo.Walk(149, 146, eBlock);
    Display("Roger waves the empty cup under the giggling red fruit, eventually enough fruit juice spills into the cup. It almost looks like human blood.");
    cEgo.AddInventory(icupofblood);
    cEgo.LoseInventory(iemptycup);
  }

  if(player.ActiveInventory == icupofblood)
  {
    cEgo.Walk(149, 146, eBlock);
    Display("You have plenty of fruit juice.");
  }
}