# With

with is a special statement like if and for.

A with statement is for running code from another object's perspective, or accessing all objects of a given type.

Make sure you understand objects and instances first, or the notion of perspective won't be clear.

As explained below, you should use with carefully. It's a complicated solution.

with changes the perspective to the instance, for the code inside.

Inside the block, you can reference the original caller object as other.

# With Object

Using with on an object is a power tool. Capable of doing a lot of work, but dangerous and easy to misuse.

with obj_article1  { // Runs for *all* article1 instances, including opponents'
    if player_id == other {
        // player_id is the instance that created the article, other is the original caller (your character for most files)
        //   so this if statement checks if the article belongs to your character.
        vsp = -1
    }
}
with <object> {
    // Code run from the perspective of *every* instance of that object.
}

This both changes perspective, and runs the code on every instance of the object. with oPlayer {... code will run on every player. This is not usually what you want, so most with blocks begin with an if check involving player_id, to only run on friendly, or enemy instances.

This lets you work with an object's instances even when you don't know how many there are; Helpful for characters with terrain or steam or other article based gimmicks.

It also lets you work with opposing players to handle status effects or other advanced behavior.

Handle with care. Prefer simpler solutions when they're available. Make sure you know which instances are involved.

Available objects

Official docs (opens new window) Recipes (opens new window)

# With Instance

// in article1_update.gml
with player_id {
    instance_create(x, y, obj_article_2)
}
with <instance> {
    // Code run from that instance's perspective
}

This changes the perspective to the single instance given. This is only needed very rarely, but is sometimes needed for a function to work properly (see list).

People sometimes use it as a shorthand to avoid using instance.variable syntax, but in practice this is almost always a bad idea. Not only does with make the code more complex, such code is usually shorter or of similar length without using with. Save it for exceptional circumstances.