Scripts and lifecycle
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
scriptis 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 signalnodeis 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,yieldor signals. - Fields declared with
varare runtime state: they are created when Play starts and discarded on Stop. Only@exportfields are saved in the scene and shown in the Inspector. Play never writes back to the edit scene. - Field initialisers must be constants (or
nilfor 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 |
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.
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")
}
}
- Animated script example The original spinner uses
ReadyandUpdateto rotate and bob.