Useful script snippets

Looping over instances

for (const inst of runtime.objects.Sprite.instances()) {
     console.log(inst.instVars.myVariable) //example of logging an instance variable
}

you can replace instances() with pickedInstances() if you want to loop over the picked instances in an event sheet script snippet

Looping over instances ordered

const instances = runtime.objects.sprite.getAllInstances();
const sortedInstances = instances.sort((a, b) => b.instVars.varName - a.instVars.varName);

for (const inst of sortedInstances)
{  
}

For loop

for (let i = 0; i < amountOfIterations; i++) {
}

Getting event sheet variables

Global variables

runtime.globalVars.variableName

Instance variables

runtime.objects.Sprite.getFirstInstance().instVars.variableName

here I am getting the first instance, you might want to use getFirstPickedInstance() or loop over all instances

Local variables

parameters in functions and custom actions are also local variables

localVars.variableName

Calling an event sheet function

runtime.callFunction("functionName", Parameter0, Parameter1, Parameter2...etc)

Returning a value in an event sheet function via scripting

runtime.setReturnValue() 

you cannot return a boolean directly, you need to first convert it into 0 or 1.

bool ? 1 : 0

Accessing by name i.e. via a string or value

in js you can access stuff via a string or variable using brackets, this is really handy and cannot be done in events. A few examples:

runtime.globalVars["myVar"]

runtime.objects[localVars.functionParam].getFirstInstance()

Getting instances by UID

in js you can get instances via their UID without requiring the object type, this can be great for generalized getters. (This is how Overboys UID to anything works) Example of returning an instances x position in an event sheet function, only by passing its UID as a parameter.

const inst = runtime.getInstanceByUid(localVars.uid);
runtime.setReturnValue(inst.x)

Last updated