Custom Molang Functions in YSM
Introduced in version 2.5.0, custom Molang functions allow model creators to write reusable scripts, respond to entity events, synchronize data across multiplayer servers, and directly override animation controllers. Instead of repeating long Molang expressions inside your animation files, you can organize your logic into clean, standalone script files.
Setting Up the Functions Directory
By default, YSM looks for your script files inside a folder named functions at the root of your model pack. If you prefer a different folder structure, you can define a custom directory inside your ysm.json manifest using the function_path property.
Each function is saved as a separate text file with the .molang extension (for example, functions/my_func.molang). Function names are case-insensitive and may only contain English letters, numbers, and underscores.
{
"files": {
"projectiles": {
"minecraft:arrow": {
"model": "models/arrow.json",
"animation": "animations/arrow.animation.json",
"texture": "textures/arrow.png"
}
},
"sound_path": "my_sounds",
"function_path": "my_functions"
}
}Writing and Calling Functions
Inside a .molang file, every statement must end with a semicolon (;). You can pass arguments into a function when calling it and read them using args[index], where the index starts at 0. You can also put expressions inside the brackets, such as args[t.a + 1]. C-style comments (// and /* ... */) are fully supported for documenting your code.
To call a custom function from an animation or another script, prefix its file name with fn. (for example, fn.my_func(10, 20)). If a function takes no arguments, you can omit the parentheses and simply write fn.my_func.
When a return statement is executed, the function stops immediately and outputs that value. Unique to custom functions, return can penetrate through {...} code blocks and break out of deeply nested loops to terminate the entire function call at once.
// Store the first argument in temporary variable t.a
t.a = args[0];
// Add the second argument and return the result
return t.a + args[1];
// Because return ended the execution above, this line will never run
q.debug_output('Meow');Chained Calls and Variable Scope
Functions can call other functions (like fn.a -> fn.b -> fn.c) or even call themselves recursively. However, the call chain depth cannot exceed 32; if it goes deeper, the call will abort and return null.
Understanding variable scope is critical when chaining functions. Temporary variables (t.*) are completely isolated per call node and expire when the call finishes. Even if a function calls itself, each call node gets its own separate t.* variables. In contrast, entity variables (v.*) are shared globally across all functions on the model.
- Create a.molang and b.molang in your functions folder.
- Use t.num in both files to test isolated scope, or v.num to test shared scope.
- Run /ysmclient molang execute fn.a in-game to observe the debug output.
// File: a.molang (Temporary variable isolation)
t.num = 111;
fn.b;
q.debug_output('fn.a: ', t.num); // Outputs 111 even though fn.b changed t.num// File: b.molang
t.num = 222;
q.debug_output('fn.b: ', t.num); // Outputs 222// File: a.molang (Shared v.* variables)
v.num = 111;
fn.b;
q.debug_output('fn.a: ', v.num); // Outputs 222 because v.num is sharedControl Flow: Conditionals and Loops
You can build multi-statement if-else branches by combining the ternary operator (? :) with curly brace blocks {...}. A condition is treated as true if its value is non-zero and non-null. Always remember to place a semicolon after the closing curly brace.
For iteration, YSM supports for_each to loop through all passed args, as well as loop(count, {...}) to repeat a block a fixed number of times. Inside loops, you can use break to exit early or continue to skip to the next iteration.
// If-else block structure
(v.b || v.c && v.d) ? {
t.a = 1;
} : {
t.a = 2;
}; // Do not forget the trailing semicolon
// Summing an arbitrary number of arguments with for_each
t.sum = 0;
for_each(t.arg, args, {
t.sum = t.sum + t.arg;
});
return t.sum;// Using loop with break and continue
v.x = 1;
v.y = 1;
loop(10, {
t.x = v.x + v.y;
v.x = v.y;
v.y = t.x;
(v.y > 20) ? break;
});
v.x = 0;
loop(10, {
(v.x > 5) ? continue;
v.x = v.x + 1;
});Subscribing to Events
You can make a function run automatically when specific lifecycle events occur by naming the file FunctionName@EventName.molang. Multiple functions can subscribe to the same event, though their execution order within that event is random.
There are three supported events: player_init (fires when a player switches to the model or the player entity loads), player_update (fires right before player animations update each frame), and sync (fires when a network sync packet arrives). If multiple events trigger simultaneously, they always run in the order: player_init > player_update > sync. Note that v.roaming variables finish synchronizing before player_init triggers.
// File: setup@player_init.molang
// Automatically initializes variables when the model loads
v.test_main = 0;Active Multiplayer Synchronization
Random numbers or certain preset variables (such as ctrl.fly) can easily become desynchronized between different clients on a multiplayer server. You can solve this by calling ysm.sync(...) to broadcast numerical values to all players loading your model.
When ysm.sync is executed, it immediately returns null asynchronously without freezing the game frame. After a network delay of several dozen milliseconds, all clients on the server will trigger any function subscribed to the @sync event using the exact same arguments.
- Create a file named test@sync.molang in your functions folder.
- Read the incoming synchronized numbers using args[0], args[1], etc.
- Call ysm.sync(1234, 5678) from a script or test it via /ysmclient molang execute ysm.sync(1234, 5678).
// File: test@sync.molang
q.debug_output('Sync complete! Arguments: ', args[0], ' and ', args[1]);Overriding Animation Controllers
Instead of building heavy Bedrock animation controllers, you can use Molang functions to directly control YSM's hardcoded animation controllers. To target a controller, replace the dot (.) in its name with _ctrl_ and prefix the file name with @. For example, to override the player.main controller, create @player_ctrl_main.molang. This script will execute automatically once every frame.
Inside the script, call ctrl.set_animation(name, loop_type) to switch animations. The second parameter is optional (defaulting to the loop mode set in Blockbench) and accepts ctrl.loop (loop infinitely), ctrl.play_once (play once and stop), or ctrl.hold_on_last_frame (hold on the final frame). Setting the same animation that is already active will be ignored unless you call ctrl.indicate_reload beforehand.
Every frame, your controller function must return a state predicate to tell the controller how to behave: ctrl.state_continue (play normally), ctrl.state_pause (pause visual playback while the timeline keeps advancing), ctrl.state_stop (smoothly stop the animation), or ctrl.state_bypass (hand control back to YSM's built-in controller logic).
// File: @player_ctrl_main.molang
v.test_main == 1 ? {
ctrl.set_animation('run');
return ctrl.state_continue;
};
v.test_main == 2 ? {
ctrl.set_animation('walk', ctrl.loop);
return ctrl.state_continue;
};
// Fall back to default built-in animations for all other values
return ctrl.state_bypass;Questions
Why do my temporary variables (t.*) reset or not carry over when I call another function?
In YSM custom functions, temporary variables (t.*) are isolated to each individual node in the call chain. Even if a function calls another function or calls itself recursively, t.* values are never shared. Use v.* variables if you need data to persist across different function calls.
Why isn't ctrl.set_animation restarting my animation when I call it again?
If you pass an animation name that matches the controller's currently active animation, the call is ignored—even if that animation has already finished playing. Call ctrl.indicate_reload (or ctrl.reset for an abrupt reset) right before ctrl.set_animation to force a reload.
Can I pass text strings or complex data through ysm.sync?
No. ysm.sync only accepts numerical arguments, and you can pass a maximum of 16 arguments per call. Passing more than 16 arguments or using non-number types will cause a parsing failure.
How do I create an event function without losing the ability to call it manually?
When you name a file setup@player_init.molang, YSM registers a function named setup that is also subscribed to the player_init event. It will run automatically on initialization, and you can still invoke fn.setup manually if needed.
Next: Molang Tips, Extra Queries, and Version Features in YSM →