Second time this week I had to cite this article:
with block recipe cards
Citing the entry titled "Count the number of instances satisfying a condition" (the condition is
belongsTo == other.id assuming that it is run from the player instance)
Code:
var my_units = 0;
with (obj_unit) {
if (belongsTo == other.id) {
my_units++;
}
}
/* Use my_units here */
It's a travesty that mainstream GML education finds it OK to teach people how to work in an instance-based environment, while at the same time neglecting to teach how to batch-handle instances.
I used to believe in
for loops in this form until I saw what was going on underneath
instance_find(), now I actively argue against it.
Whenever
instance_find() is called, it iterates through the list of instances anew to find an instance. In contrast, a
with block picks up all instances specified en-passant. Your
for loop is covertly a quadratic time lookup, while the equivalent
with block is genuinely linear time.