Bedrock Wiki
  • Discord
  • Contribute
  • bedrock.dev
  • MS Learn
Beginner's Guide
  • Guide
    • 1. Introduction
      guide
    • 2. Add-Ons Explained
    • 3. Software & Preparation
    • 4. Project Setup
    • 5. Create a Custom Item
    • 6. Create a Custom Entity
    • 7. Blockbench: Modeling, Texturing & Animating
    • 8. Adding a Loot Table, Spawn Rule & Crafting Recipe
  • Extra
    • a. Understanding JSON
    • b. Download Example Packs
    • c. Troubleshooting
      help
    • d. Advanced Manifest
    • e. Format Versions
    • f. Project Setup Android
Animation Controllers
  • Intro to Animation Controllers
    guide
  • Entity Commands
  • AFK Detector
  • Death Commands
  • Molang into Scoreboard
  • Respawn Commands
Blocks
  • General
    • Intro to Blocks
      guide
    • Block Components
    • Block Tags
    • Block States
    • Block Traits
    • Block Permutations
    • Block Events
      Scripts
    • Block Event Migration
      help
    • Blocks as Items
    • Multi-Blocks
    • Troubleshooting Blocks
      help
  • Sound & Visuals
    • Intro to Block Visuals
      guide
    • Block Culling
    • Block Models
      guide
    • Block Sounds
    • Block Texture Animation
    • Block Texture Variation
    • Block Tinting
  • Tutorials
    • Applying Effects
      Scripts
    • Avoiding State Limit
    • Block Orientation
    • Fake Blocks
      Scripts
    • Intercardinal Orientation
      Scripts
    • Ore Loot Tables
      Scripts
    • Tool-Based Destruction
  • Vanilla Re-Creations
    • Custom Crops
      Scripts
    • Custom Glass
    • Custom Glazed Terracotta
    • Custom Heads
      Scripts
    • Custom Trapdoors
      Scripts
  • Documentation
    • Block Format History
    • Block Shapes
    • Redstone Components
    • Vanilla Block Models
    • Vanilla Block Sounds
    • Vanilla Block Tags
    • Vanilla Voxel Shapes
Commands
  • General
    • Intro to Command Blocks
    • Understanding Selectors
    • Functions
      guide
    • Block States
    • Coordinate System
    • Giving NBT Items
    • Scoreboard Operations
  • Commands
    • Damage
    • Execute
    • Playanimation
    • Playsound
  • On Event Systems
    • On First World Load
      function
    • On Player First Join
    • On Player Join
    • On Player Leave
    • On Player Death
    • On Player Respawn
  • Scoreboard Systems
    • Entity Counter
    • Scoreboard Timers
    • Comparing And Retrieving Scores
  • Detection Systems
    • Look Detection
    • Item Drop Detection
    • Movement Detections
    • Rain Detection
  • Techniques
    • Execute Logic Gates
      concept
    • Execute at Block Variant
    • Execution Forking
      concept
    • Binary in Commands
      concept
    • MBE - Max's Block Entity
    • FMBE - A New Way to Create Display Entities
    • Dynamic Displays
    • Orbital Camera
  • Useful Creations
    • Sphere Command
    • Compass Display
    • Custom Crafting
    • Multiplayer Position Rearrangement
      function
Concepts
  • contents.json
  • Molang
  • Namespaces
  • Overwriting Assets
  • Shaders
  • Sounds
  • Subpacks
  • Texture Atlases
  • textures_list.json
Documentation
  • Advanced Molang
  • File Types
  • Fog IDs
  • Material Configuration Description
  • Molang Queries
  • Pack Folder Structure
  • Shared Constructs
  • Sound Definitions
  • Vanilla Materials
Entities
  • General
    • Intro to Entities BP
      guide
    • Intro to Entities RP
      guide
    • Troubleshooting Entities
      help
    • Entity Events
    • Entity Properties
    • NPC Dialogue
    • Render Controllers
    • Spawn Rules
  • Tutorials
    • Area Effect Clouds
    • Coordinate Space Conversion
    • Creating Boats
    • Detecting Other Entities
    • Disabling Team Damage
    • Dummy Entities
    • Entity Attacks
    • Entity Movement
    • Entity Timers
    • Holding Items
    • Invulnerable Entities
    • Look at Entity
    • Riding Flying Entities
    • Sleeping Entities
    • Solid Entities
    • Spawning Tamed Entities
      Scripts
    • Village Mechanic
  • Documentation
    • Dummy Components
    • Non-Mob Runtime Identifiers
    • Projectiles
    • Runtime Identifiers
    • Vanilla Usage Components
    • Vanilla Usage Spawn Rules
Items
  • General
    • Intro to Items
      guide
    • Item Components
    • Item Tags
    • Item Events
      Scripts
    • Item Event Migration
      help
    • Item Catalog
    • Troubleshooting Items
      help
  • Tutorials
    • Equipment-Based Commands
    • Spawning Items
    • Throwable Items
  • Vanilla Re-Creations
    • Custom Armor
    • Custom Food
      Scripts
    • Custom Pottery Sherds
    • Custom Weapons
  • Documentation
    • Enchantments
    • Attachables
    • Item Format History
    • Numerical Item IDs
    • Vanilla Item Groups
    • Vanilla Item Tags
    • Vanilla Usage Components
JSON UI
  • General
    • Intro to JSON UI
      guide
    • Best Practices
      guide
  • Tutorials
    • Adding HUD Elements
    • Aseprite Animations
    • Buttons and Toggles
    • Modifying Server Forms
    • Preserve Title Texts
    • String to Number
  • Documentation
    • JSON UI Documentation
Loot, Recipes & Trading
  • General
    • Trading Behavior
  • Documentation
    • Loot Tables
    • Trade Tables
    • Recipes
    • Item Functions
  • Tutorials
    • Randomized Structure Loot
Meta
  • Add-On Performance
  • Style Guide
  • Useful Links
  • Using Schemas
  • Version Control
  • Q&A
    • Blocks and Items Q&A 2024/08/30
    • Deferred Technical Preview Q&A 2024/02/23
    • GameTest Q&A 2021/08/06
    • Scripting and Editor Q&A 2023/09/22
    • World Generation Q&A 2024/11/15
NBT
  • General
    • .mcstructure
  • Tutorials
    • Enabling Experiments by Editing NBT
    • Extending Structure Limits
  • NBT in Depth
    • About NBT (Named Binary Tag)
    • NBT Libraries
    • Reading NBT Example
Particles
  • General
    • Intro to Particles
      guide
  • Tutorials
    • Disabling Particles
  • Documentation
    • Vanilla Particles
Scripting
  • General
    • Intro to Scripting
    • What is Script API?
    • API Modules
  • Tutorials
    • Script Core Features
    • Block Placement Prevention
    • Custom Commands
    • GameTests
    • Script Privileges
    • Script Requests API
    • Server Forms
  • Documentation
    • Engine Environment
    • Script Resources
    • Script Watchdog
    • Troubleshooting JavaScript
    • TypeScript
Servers
  • Software
    • Bedrock Server Software
  • Protocols
    • Bedrock Protocol
    • NetherNet Protocol
    • RakNet Protocol
Text & Localization
  • General
    • Intro to Text & Localization
    • Raw Text
    • Splashes
  • Emojis & Symbols
    • Fonts
    • Intro to Emojis
    • Custom Emojis
    • Input Keys
Visuals
  • General
    • Introduction to Entity Visuals
      guide
    • Bedrock Modeling
    • Custom Death Animations
    • Effects in Animations
    • Material Creations
    • Materials
    • Math-Based Animations
    • Skin Packs
  • Tutorials
    • Entity Texture Animation
    • Glowing Entity Texture
    • Hurt Animations
    • Leash Position
    • Player Geometry
    • Remove Entity Shadows
    • Retexturing Spawn Eggs
  • Ideas
    • Structure Presentation
World Generation
  • General
    • Intro to World Generation
      guide
    • Biomes
      guide
    • Feature Types
    • Jigsaw Structures
  • Tutorials
    • Block Conditions for Features
    • Generating Custom Ores
    • Generating Custom Structures
    • Generating Patches
    • Heightmap Noise
  • Documentation
    • Biome Tags

Script Core Features

Script Core Features
  • Setup
  • Events
    • World Events
    • System Events
    • Script Events
  • Scheduling
    • Scheduling Timers
    • Clearing Timers
  • Saving and Loading data
    • Get & Set Dynamic Properties
  • Removing Entities
  • Running Commands
    • Avoid Running Commands in Script

WARNING

The Script API is currently in active development, and breaking changes are frequent. This page assumes the format of Minecraft 1.26.20

The Script API, with most core features being implemented in the @minecraft/server module, contains many methods to interact with Minecraft world, including entities, blocks, dimensions, and more. This article contains a basic introduction to some of the core API mechanics. For more detailed information, please visit the Microsoft Learn documentation pages.

Setup ​

You will need to add the script module as a dependency in your manifest.json.

BP/manifest.json
json
{
    "dependencies": [
        {
            "module_name": "@minecraft/server",
            "version": "2.7.0"
        }
    ]
}
1
2
3
4
5
6
7
8

Events ​

The Script API's @minecraft/server module uses its own event-driven architecture, making it possible to execute code when a specific event occurs by subscribing to an event listener.

There are generally two types of events: before events, and after events.

  • Before events fire before an action happens in read-only mode, and are cancellable (with a few exceptions).
  • After events fire after an action happens, and are not cancellable.

World Events ​

World event APIs provides many event listeners that fire when a specific type of event happen in a Minecraft world, such as chatSend, entityHurt, playerSpawn, worldLoad and more.

Further information

Check the Microsoft Learn documentation to see what world events are available within Minecraft:

  • Before events fire before an event happens and are read-only, but can be canceled. See the beforeEvent documentation.
  • After events fire after an event has run and cannot be canceled. See the afterEvent documentation.
  • It is good practice to always use after events, unless if there is a good reason not to, such as needing to cancel them.

In this example, we aim to send the player a message each time they break a block. We do this by subscribing to the playerBreakBlock after event, extracting its data, and then sending the player a message with that extracted data.

js
import { world } from "@minecraft/server";

// subscribing to the block break event
// fires when a player breaks a block
world.afterEvents.playerBreakBlock.subscribe((event) => {
    const player = event.player; // Player that broke the block for this event.
    const block = event.block; // Block impacted by this event. Note that the typeId of this block will ALWAYS be air, as the player has just broken it.
    const permutation = event.brokenBlockPermutation; // Returns permutation information about this block before it was broken.
    player.sendMessage(
        `You have broken ${permutation.type.id} at ${block.x}, ${block.y}, ${block.z}`
    ); // Sends a message to player.
});
1
2
3
4
5
6
7
8
9
10
11
12

System Events ​

System events fire when a specific type of event happens in the broader scope of the Minecraft add-on system, as opposed to events that happen in the game world itself.

Further information

Check the Microsoft Learn documentation to see what system events are available within Minecraft:

  • Before events fire before an event happens and are read-only, but can be canceled. See the beforeEvent documentation.
  • After events fire after an event has run and cannot be canceled. See the afterEvent documentation
  • Both types of events are used for different purposes.

In this example, we got tired of our add-on being shutdown by the scripting watchdog. To resolve this, we'll cancel its shutdown order.

We first get the beforeEvents property of the system object, then we subscribe to the watchdogTerminate event. This allows us to use the API to stop the performance watchdog from closing the world when its running scripts exceed performance boundaries, which are dependent on the configuration of the script environment.

js
import { system } from "@minecraft/server";

// subscribing to the watchdogTerminate event
system.beforeEvents.watchdogTerminate.subscribe((event) => {
    event.cancel = true; // Cancel the world from closing down. This will terminate the script engine instead.
    console.warn("Canceled critical exception of type " + event.terminateReason); // Print a message to the console if this event fires.
}); // Take that watchdog, no shutting us down now!!
1
2
3
4
5
6
7

Script Events ​

Script events, not to be confused with world events or system events, allow us to respond to inbound /scriptevent commands by subscribing to the scriptEventReceive event handler. This event fires when the /scriptevent command is invoked by a player, NPC, or block. More information on this event can be found in the Script Event Documentation page.

The /scriptevent command has the following syntax:

/scriptevent <messageId: string> <message: string>
1
  • messageId in the /scriptevent command can be received in API via ScriptEventCommandMessageEvent.id
  • message in the /scriptevent command can be received in API via ScriptEventCommandMessageEvent.message

Example

Command input:

/scriptevent wiki:test Hello World
1

What the event listener returns:

js
import { system } from "@minecraft/server";

system.afterEvents.scriptEventReceive.subscribe((event) => {
    const {
        id, // returns string (wiki:test)
        initiator, // returns Entity (or undefined if an NPC did not fire the command)
        message, // returns string (Hello World)
        sourceBlock, // returns Block (or undefined if a block did not fire the command)
        sourceEntity, // returns Entity (or undefined if an entity did not fire the command)
        sourceType, // returns MessageSourceType (can be 'Block', 'Entity', 'NPCDialogue', or 'Server')
    } = event;
});
1
2
3
4
5
6
7
8
9
10
11
12

TIP

When a /scriptevent is fired from an NPC dialogue button, sourceType will be "NPCDialogue". In this case:

  • initiator is the player who clicked the button.
  • sourceEntity is the NPC entity that ran the command.

Always use initiator to get the player in NPC-triggered events. sourceEntity will not be a player in this context.

js
system.afterEvents.scriptEventReceive.subscribe((event) => {
    const player = event.initiator; // the player, when fired from an NPC button
    if (!player || player.typeId !== "minecraft:player") return;
    // ...
});
1
2
3
4
5

When the event comes from a command block, both initiator and sourceEntity will be undefined. If you need to target a specific player from a command block, pass the player name inside message and look them up:

js
const player = world.getAllPlayers().find((p) => p.name === event.message.trim());
1

TIP

You can filter which namespaces a subscriber receives by passing a namespaces option. This avoids one large handler processing every scriptevent in your pack:

js
system.afterEvents.scriptEventReceive.subscribe(
    (event) => {
        /* only receives wiki:shop events */
    },
    { namespaces: ["wiki_shop"] }
);
1
2
3
4
5
6

Scheduling ​

We may decide to execute a function at a certain time in the future. This is known as "scheduling a call".

When using the Script API, native JavaScript functions like setTimeout and setInterval do not exist in the scripting runtime. Minecraft instead has its own scheduling methods, which work using game ticks instead of real time.

These methods can be accessed from the system object obtained by importing.

js
import { system } from "@minecraft/server";
1

Scheduling Timers ​

system.run(callback: () => void): number - Runs a specified function at the next available future time. This is frequently used to implement delayed behaviors and game loops. When run within the context of an event handler, this will generally run the code at the end of the same tick where the event occurred. When run in other code (a system.run callout), this will run the function in the next tick. Note that, depending on the load of the system, running in the same or next tick is not guaranteed.

js
import { system, world } from "@minecraft/server";

system.run(() => {
    world.sendMessage("This runs one tick after the previous tick");
});
1
2
3
4
5

system.runInterval(callback: () => void, tickInterval?: number): number - Runs a set of code repeatedly, starting after the first interval of time, and then repeating continuously forever with that interval.

js
import { system, world } from "@minecraft/server";

system.runInterval(() => {
    world.sendMessage("This message runs every 20 ticks (once per second)");
}, 20);
1
2
3
4
5

system.runTimeout(callback: () => void, tickDelay?: number): number - Runs a function once after the interval of time has elapsed.

js
import { system, world } from "@minecraft/server";

system.runTimeout(() => {
    world.sendMessage("This message runs once once 20 ticks has passed.");
}, 20);
1
2
3
4
5

system.runJob(generator: Generator<void, void, void>): number - Queues a generator function to run until completion. The generator will be given a time slice each tick, and will be run until it yields or completes. For more information, see the MDN generator function reference.

js
import { system, world } from "@minecraft/server";

function* blockPlacingGenerator(size, startX, startY, startZ) {
    const overworld = world.getDimension("overworld"); // gets the dimension of type overworld.
    for (let x = startX; x < startX + size; x++) {
        for (let y = startY; y < startY + size; y++) {
            for (let z = startZ; z < startZ + size; z++) {
                const block = overworld.getBlock({ x: x, y: y, z: z }); // get the block at the current loop coordinates.
                if (block) block.setType("minecraft:cobblestone"); // if the block is loaded, set it to cobblestone.
                // yield back to job coordinator after every block is placed
                yield;
            }
        }
    }
}
// builds a 10x10x10 cube of cobblestone starting at overworld location -2, -60, 1.
system.runJob(blockPlacingGenerator(10, -2, -60, 1));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Clearing Timers ​

system.clearRun(runId: number): void - Cancels the execution of a function run that was previously scheduled via the run, runTimeout or runInterval function.

js
import { system, world } from "@minecraft/server";

const callbackId = system.runInterval(() => {
    world.sendMessage("Running every tick");
});

system.runTimeout(() => {
    system.clearRun(callbackId); // stops the system.runInterval callback from running after 20 ticks
    world.sendMessage("Stopped");
}, 20);
1
2
3
4
5
6
7
8
9
10

system.clearJob(jobId: number): void - Cancels the execution of a job queued via the runJob function.

js
import { system, world } from "@minecraft/server";

function* blockPlacingGenerator(size, startX, startY, startZ) {
    const overworld = world.getDimension("overworld");
    for (let x = startX; x < startX + size; x++) {
        for (let y = startY; y < startY + size; y++) {
            for (let z = startZ; z < startZ + size; z++) {
                const block = overworld.getBlock({ x: x, y: y, z: z });
                if (block) block.setType("minecraft:cobblestone");
                yield;
            }
        }
    }
}

const callbackId = system.runJob(blockPlacingGenerator(10, -2, -60, 1));

system.runTimeout(() => {
    system.clearJob(callbackId); // stops the system.runJob callback from running after 20 ticks
    world.sendMessage("Stopped");
}, 20);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

More information regarding the inner functionality of the system scheduling methods can be found on the Microsoft Learn Game Loops & Timed Callbacks page.

Saving and Loading data ​

With the @minecraft/server module, developers can define their own custom properties, known as dynamic properties, that can be used and stored within Minecraft. This data is stored specifically in the world's db folder using the behavior pack header UUID.

Compound DynamicProperties

Compound 8a121475-6f9f-4780-a746-2bf25f732204 — Header UUID of the behavior pack

String myColorProperty: "orange"

Byte hasOwnerDied: false

In order to save data, the property must first be initialized. There are multiple ways to declare dynamic properties, either on an entity, world, or item. You can define as many numbers and booleans as you would like, however Minecraft API only allows each - behavior pack to save a limited amount of data per dynamic property.

  • String dynamic properties can be a maximum of 32767 characters in length.
  • Number dynamic properties can be a maximum of the 64-bit float limit (-1.7976931348623158e+308 to -2.2250738585072014e-308, or from 2.2250738585072014e-308 to 1.7976931348623158e+308).

Get & Set Dynamic Properties ​

To get and set dynamic properties, you can use the getDynamicProperty and setDynamicProperty methods.

TIP

It is important to note that getting a dynamic property does not guarantee it has a value saved. When getting the property for the first time, the method returns undefined.

With this in mind, here are some examples of how to get and set dynamic properties in Minecraft:

js
import { system, world } from "@minecraft/server";

system.runInterval(() => {
    world.getPlayers().forEach((player) => {
        // run code for each player the array returns.
        // all three properties are unique to each player, similar to tags/scoreboard data.
        player.setDynamicProperty("number_value", 12); // sets a number property on the player.
        player.setDynamicProperty("string_value", "This is a string :)"); // string property
        player.setDynamicProperty("boolean_value", true); // boolean property
    });
}, 20); // run this interval once every 20 game ticks.

world.afterEvents.playerBreakBlock.subscribe((data) => {
    // subscribe to the block break event.
    const player = data.player; // define the player variable for use later.
    const numberProperty = player.getDynamicProperty("number_value"); // get the dynamic property that was saved.
    player.sendMessage(`You have a property of value ${numberProperty}!`); // print the players saved value to the chat.
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

Here is an example of how to get and set dynamic properties at the global level:

js
import { world } from "@minecraft/server";

world.setDynamicProperty("player_score", 100); // set a property with a number value
const playerScore = world.getDynamicProperty("player_score"); // get the previously set property- will return 100.
1
2
3
4

Removing Entities ​

The Script API provides two ways to remove an entity, which behave differently:

  • entity.kill() — triggers the entity's death sequence. It fires the entityDie event, causes drops, plays the death animation, and counts as a kill for scoreboard objectives.
  • entity.remove() — removes the entity immediately and silently. No death event, no drops, no animation.
js
// Use kill() when you want the full death behavior (drops, events, kill credit)
zombie.kill();

// Use remove() when you want silent cleanup with no side effects
// For example, removing dropped item entities from the ground
for (const item of dimension.getEntities({ type: "minecraft:item" })) {
    item.remove();
}
1
2
3
4
5
6
7
8

TIP

Using kill() on dropped item entities will fire entityDie for each one and may trigger unintended listeners. Always use remove() for item cleanup.

Running Commands ​

Entity::runCommand() and Dimension::runCommand() allows the API to run a particular command synchronously from the context of the broader dimension. Always try to avoid runCommand calls wherever possible, and use built-in API methods instead. As runCommand fires synchronously, you'll need to schedule its call if you are in read-only mode.

In this example, we're sending a message that foreshadows how an entity is about to get damaged. As runCommand cannot be called in read-only mode, we will need to defer its execution using system.run(). The entity will run the command after it gets damaged, saying "OWW!!".

js
import { system, world } from "@minecraft/server";

// callbacks for a before event run in read-only mode
world.beforeEvents.entityHurt.subscribe((event) => {
    const { hurtEntity, cancel } = event;

    // send a message foreshadowing impending damage
    world.sendMessage(`${hurtEntity.nameTag} is about to get hurt!`);

    // only you, reader, can save this entity from getting hurt
    // your heroic action: uncommenting the next two lines
    // cancel = true;
    // return;

    // defer the command to run outside of read-only mode
    system.run(() => {
        // sadly, once this command runs, it will be too late to stop the entity from being hurt
        hurtEntity.runCommand("say OWW!!");
    });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Avoid Running Commands in Script ​

Normally we recommend that you avoid using commands in script, because it's slow to run a command from the Script API, and server performance starts to slow down as more commands are executed over time. The following command features, however, are not implemented in the scripting API, which leaves us with no choice but to use runCommand instead.

kick

To kick players, the @minecraft/server-admin module must be used. This module, however, is only available on Bedrock Dedicated Servers.

  • Outside of Bedrock Dedicated Servers, the /kick command must be used

setblock

  • Script API cannot destroy blocks like /setblock ... destroy.
  • It is possible to set a block, however
  • Getting the loot from a block if it were to be mined can be done with the LootTableManager.

Player abilities

  • Script API cannot set abilities for each player.
  • You cannot read player abilities.

execute

  • Script API can utilize new execute syntax to run commands with lots of if/unless conditions for simplicity or performance.

Minecraft functions

  • Script API cannot run Minecraft function files without the use of /function.

locate

  • Script API cannot get a structure location.
  • Cannot get a biome location.

weather

  • Script API cannot get/set the world weather.

mobevent

  • Script API cannot enable/disable mobevents.

fog

  • Script API cannot manage active fog settings for players.

stopsound

INFO

At time of writing, the Player::stopSound method is in experimental.

  • Script API cannot stop playing a sound. Music can be stopped using World::stopMusic() or Player::stopMusic().

dialogue

INFO

At time of writing, the EntityNpcComponent class is in experimental.

  • There is no dedicated Script API method for NPC dialogues, however you can use player.runCommand("dialogue open @e[tag=npc,r=5] @s scene_tag") or dimension.runCommand(...) as a workaround to open and change NPC dialogues from script.
  • The Script API can't open the NPC dialogue to the player.
  • It cannot change the dialogue displayed by an NPC.

Contributors

Edit Script Core Features on GitHub

Bedrock Wiki by Bedrock OSS

"Minecraft" is a trademark of Mojang AB.

Bedrock OSS, Bedrock Wiki and bedrock.dev are not affiliated in any way with Microsoft or Mojang AB.

  • Privacy Policy
  • Join our Discord
  • Learn how to Contribute
  • Visit our Repository