Newbie Question about custom commands

Trev0rc
18 Jul 2020, 18:23

Hi, I'm following the tutorial and trying to add a custom command 'weigh' to the game object. I'm using 5.8.0 and the tutorial seems a bit out of date in places. So I cannot add the test for a 'weight' attribute in the way the tutorial describes.
So my script looks like:

if (HasAttribute(this, "weight")) {
msg ("The " + object.name + " weighs " + object.weight + " grams.")
}
else {
msg ("You cannot estimate the weight of that")
}

The script looks ok but the 'else' condition always happens regardless of whether the object has a weight attribute. This seems like a fundamental concept so I must be doing something wrong.

Advice gratefully received.


mrangel
18 Jul 2020, 19:36

if (HasAttribute(this, "weight")) { should be if (HasAttribute(object, "weight")) {.

The variable this always refers to the thing that you select in the editor when want to you edit the script. For a verb, that's the object. For a custom command, this means the command itself. So you want to use object to refer to the object.


Trev0rc
19 Jul 2020, 17:24

Excellent thanks. That works. Unfortunately the IDE does not let you select 'object' without also typing the name of a specific object. But you can switch to code mode and enter HasAttribute(object, "weight") so its not too much of a pain.
Thanks again for the quick reply.


mrangel
19 Jul 2020, 20:01

I've not used the IDE much. But for the most part, choosing "Expression" will help.
In this context, both HasAttribute (object, "weight") and the variable name object are considered expressions.