The VScript Book

Chapter 2.3: Entity Scripts and self

The real power of VScript comes from attaching scripts directly to other entities. Almost any entity in Hammer (a prop_dynamic, a func_button) can have a script attached to it via its vscripts keyvalue.

If you have ten turrets, you can give each one the same script, and each will run its own independent version of that script.

self: The Most Important Variable

When a script is attached to an entity, VScript gives it a special variable named self.

self is a script handle. It's your script's connection to the entity it's attached to. It's how you tell the turret to fire, or the door to open.

[Door Entity in Map]
self
[Door's Script Scope]
function OpenTheDoor() {...}

Using self to Act

You use self to call methods (functions) that affect the entity. Think of it as telling the entity to do something to itself.

// This script is attached to a cube (prop_physics).
// It defines a function that can be called to change the cube's color.

function TurnRed() {
    // 'self' here refers to THIS specific cube.
    // We call the SetColor method on it to change its render color.
    EntFireByHandle(self, "Color", "255 0 0", 0, null, null) // Sets color to Red
    printl(self.GetName() + " is now red!")
}

// To use this, you would create an output from another entity (like a button)
// targeting this cube, and use the "RunScriptCode" input with the parameter "TurnRed()".