# Scripts and lifecycle

> Aego 0.12.5 · development; docs build `4a32b816933e02930662f6a443cb25abe6050d090c55e237cbff5c44ae9b25f8`. [Build manifest](/docs-build.json).

```aes
script Enemy {
	@export var Speed float = 120
	var elapsed float

	signal Died()

	func Ready() {}
	func FixedUpdate(dt float) {}
	func Update(dt float) {}
	func Reloaded() {}

	func helper() int { return 1 }
}
```

- A `script` is a stateful type that attaches to a node. A node holds at most one instance of each script type; different script types may share a node.
- Every script has an implicit field `node NodeRef`. Naming a field, method or signal `node` is an error.
- Methods are declared inside the script and called unqualified from other methods. Package-level functions see no script state and cannot use `node`, `start`, `yield` or signals.
- Fields declared with `var` are runtime state: they are created when Play starts and discarded on Stop. Only `@export` fields are saved in the scene and shown in the Inspector. Play never writes back to the edit scene.
- Field initialisers must be constants (or `nil` for references and handles).

Lifecycle methods are recognised by name and must have exactly these signatures:

| Method | When |
|---|---|
| `func Ready()` | once, after every instance in the scene exists and references are resolved, in scene pre-order |
| `func FixedUpdate(dt float)` | every fixed step, before physics, in instance creation order |
| `func Update(dt float)` | every frame, in instance creation order |
| `func Reloaded()` | after a hot reload, for every instance whose script or a dependency's interface changed; see [Hot reload](/language/hot-reload.md) |

Instances that do not declare a method are not visited for it; a scene with ten thousand instances that never declare `Update` costs nothing in the update phase. Lifecycle methods cannot be coroutines (`AES2056`), cannot be signal handlers (`AES2055`) and cannot be called through a `ScriptRef` (`AES2059`).

Run it: the sandbox attaches each script to its own node.

```aes run
package demo

import "aego/log"

script Enemy {
    @export var Speed float = 2

    var fixedSteps int
    var frames int
    var elapsed float

    func Ready() {
        log.Info("Ready on " + node.Name() + ", speed " + string(Speed))
    }

    func FixedUpdate(dt float) {
        fixedSteps++
    }

    func Update(dt float) {
        frames++
        elapsed += dt
        node.SetPosition(node.Position() + Vec2{Speed * dt, 0})
        if frames % 40 == 0 {
            log.Info("frame " + string(frames) + ", fixed steps " + string(fixedSteps) + ", elapsed " + string(elapsed) + ", x " + string(node.Position().X))
        }
    }

    func helper() int {
        return frames
    }
}

script Spawner {
    func Ready() {
        log.Info("Ready on " + node.Name() + "; every Ready runs before the first Update")
    }
}
```
