ScriptRef
node.GetScript<T>() returns the ScriptRef<T> of script T on that node, or nil when the node has none. On a nil or destroyed node it faults with AES6004. Use pkg.Name when the short name is ambiguous (AES2058).
Through a ScriptRef you can read and write fields (exported ones from other packages), call plain methods and connect to signals. Lifecycle methods and coroutines are not reachable (AES2059); call a plain method that does the work, or connect to a signal. A ScriptRef is re-validated on every access; once the target instance stops, access faults with AES6004. ScriptRef fields cannot be exported. A ScriptRef survives a hot reload of either side: fields and methods are re-resolved by name.
Run it:
package demo
import "aego/log"
script Health {
@export var Max int = 10
var Current int
signal Died()
func Ready() {
Current = Max
}
func Damage(n int) {
Current -= n
if Current <= 0 {
Current = 0
Died.Emit()
}
}
}
script Attacker {
var target ScriptRef<Health>
var conn Connection
var frames int
func Ready() {
other := node.Find("/Health")
target = other.GetScript<Health>()
conn = target.Died.Connect(OnTargetDied)
}
func Update(dt float) {
frames++
if frames % 20 == 0 && target.Current > 0 {
target.Damage(4)
log.Info("hit, target has " + string(target.Current) + " of " + string(target.Max))
}
}
func OnTargetDied() {
log.Info("target died on frame " + string(frames))
conn.Disconnect()
}
}