脚本Script文档

版本: 1.16.200.2(正式版)

此文档已有已翻译版本

*请前往API 文档>其它文档>脚本 查看


Script API Objects

Here you can find the definition of some objects returned by the script API.

Entity JS API Objectsdf

NameTypeEntity JS API ObjectDescription
__identifier__StringREAD ONLY. This is the identifier for the object in the format namespace:name. For example, if the type is entity and the object is representing a vanilla cow, the identifier would be minecraft:cow
__type__StringREAD ONLY. This defines the type of object. Can be: "entity" or "item_entity".
idPositive IntegerREAD ONLY. This is the unique identifier of the entity.

Level JS API Object

NameTypeLevel JS API ObjectDescription
__type__StringREAD ONLY. This defines the type of object. Will be: "level".
level_idPositive IntegerREAD ONLY. This is the unique identifier of the level.

Component JS API Object

NameTypeComponent JS API ObjectDescription
__type__StringREAD ONLY. This defines the type of object. Will be: "component".
dataJavaScript ObjectThis is the content of the component.

Query JS API Object

NameTypeQuery JS API ObjectDescription
__type__StringREAD ONLY. This defines the type of object. Will be: "query".
query_idPositive IntegerREAD ONLY. This is the unique identifier of the query.

ItemStack JS API Object

NameTypeItemStack JS API ObjectDescription
__identifier__StringREAD ONLY. This is the identifier for the object in the format namespace:name. For example, if the type is entity and the object is representing a vanilla cow, the identifier would be minecraft:cow
__type__StringREAD ONLY. This defines the type of object. Will be: "item_stack".
countStringREAD ONLY. This is the number of items in the stack.
itemStringREAD ONLY. This is the identifier of the item.

Block JS API Object

NameTypeBlock JS API ObjectDescription
__identifier__StringREAD ONLY. This is the identifier for the object in the format namespace:name. For example, if the type is block and the object is representing a block of bedrock, the identifier would be minecraft:bedrock
__type__StringREAD ONLY. This defines the type of object. Will be: "block".
block_positionJavaScript ObjectREAD ONLY. This is the position of the block and it functions as part of its unique identifier.

Parameters

NameTypeDescription
xIntegerThe x position
yIntegerThe y position
zIntegerThe z position
ticking_areaJavaScript Object

Ticking Area JS API Object#

Entity Ticking Area JS API Object#

NameTypeEntity Ticking Area JS API ObjectDescription
__type__StringREAD ONLY. This defines the type of object. Will be: "entity_ticking_area".
entity_ticking_area_idPositive IntegerREAD ONLY. This is the unique identifier of the ticking area.

Level Ticking Area JS API Object#

NameTypeLevel Ticking Area JS API ObjectDescription
__type__StringREAD ONLY. This defines the type of object. Will be: "level_ticking_area".
level_ticking_area_idStringREAD ONLY. This is the unique identifier of the ticking area.

Script Bindings#

Bindings are the capabilities of the Minecraft Script Engine to change or modify things in the game.

Logging Bindings#

log(Message)#

The log function is accessed through the server or client objects and allows for logging a message to the ContentLog file. On Windows 10 devices it is located at ' %APPDATA%\..\Local\Packages\Microsoft.MinecraftUWP_8wekyb3d8bbwe\LocalState\logs '

Parameters#

NameTypeDescription
MessageStringThe message that you want to send to the log file

Code Example:

Log

system.exampleFunction = function() {
  client.log("example log message") 
}; 

Entity Bindings#

createEntity()#

NOTE: Entities are created first on the server, with the client notified of new entities afterwards. Be aware that if you send the result object to the client right away, the created entity might not exist on the client yet.

Return Value#

TypeValue
Entity JS API ObjectAn object representing the newly created entity

createEntity(Type, TemplateIdentifier)#

NOTE: Entities are created first on the server, with the client notified of new entities afterwards. Be aware that if you send the result object to the client right away, the created entity might not exist on the client yet.

Parameters#

NameTypeDescription
TemplateIdentifierStringThis can be any of the entity identifiers from the applied Behavior Packs. For example specifying minecraft:cow here will make the provided entity a cow as defined in JSON
TypeStringSpecifies the type of the entity that is being created by the template. Valid inputs are entity and item\_entity

Return Value#

TypeValue
Entity JS API ObjectAn object representing the newly created entity

destroyEntity(EntityObject)#

Parameters#

NameTypeDescription
EntityObjectEntity JS API ObjectThe object that was retrieved from a call to createEntity() or retrieved from an entity event

Return Value#

TypeValue
BooleanThe entity was successfully destroyed

isValidEntity(EntityObject)#

Parameters#

NameTypeDescription
EntityObjectEntity JS API ObjectThe object that was retrieved from a call to createEntity() or retrieved from an entity event

Return Value#

TypeValue
BooleanThe entity is in the Script Engine's database of entities

Component Bindings#

registerComponent(ComponentIdentifier, ComponentData)#

Parameters#

NameTypeDescription
ComponentDataJavaScript ObjectA JavaScript Object that defines the name of the fields and the data each field holds inside the component.
ComponentIdentifierStringThe identifier of the custom component. It is required to use a namespace so you can uniquely refer to it later without overlapping a name with a built-in component: for example 'myPack:myCustomComponent'

Return Value#

TypeValue
BooleanThe component was successfully registered

Code Example:

Registering a custom component

const mySystem = server.registerSystem(0, 0);

mySystem.initialize = function() {
  this.registerComponent("myPack:myCustomComponent", { myString: "string", myNumber: 0, myBool: true, myArray: [1, 2, 3] });
};

createComponent(EntityObject, ComponentIdentifier)#

Parameters#

NameTypeDescription
ComponentIdentifierStringThe identifier of the component to add to the entity. This is either the identifier of a built-in component (check the Script Components section) or a custom component created with a call to registerComponent()
EntityObjectEntity JS API ObjectThe EntityObject that was retrieved from a call to createEntity() or retrieved from an event

Return Value#

TypeValue
Component JS API ObjectAn object with the following fields, and additionally, all the fields as defined in the component

Code Example:

Creating a custom component

let globals = {
  ready: false
};

const mySystem = server.registerSystem(0, 0);

mySystem.initialize = function() {
  this.registerComponent("myPack:myCustomComponent", { myString: "string", myNumber: 0, myBool: true, myArray: [1, 2, 3] });
}

mySystem.update = function() {
  if(globals.ready == false) {
    globals.ready = true;
    let myEntity = this.createEntity();
    if(myEntity != null) {
      let myComponent = this.createComponent(myEntity, "myPack:myCustomComponent");
    }
  }
};

hasComponent(EntityObject, ComponentIdentifier)#

Parameters#

NameTypeDescription
ComponentIdentifierStringThe identifier of the component to check on the entity. This is either the identifier of a built-in component (check the Script Components section) or a custom component created with a call to registerComponent()
EntityObjectEntity JS API ObjectThe EntityObject that was retrieved from a call to createEntity() or retrieved from an event

Return Value#

TypeValue
BooleanThe EntityObject has the component

Code Example:

Check whether an entity has specified component

let globals = {
  ready: false
};

const mySystem = server.registerSystem(0, 0);

mySystem.update = function() {
  if(globals.ready == false) {
    globals.ready = true;
    let entity = this.createEntity("entity", "minecraft:pig");
    if(this.hasComponent(entity, "minecraft:nameable")) {
      // Do some work
    }
  }
};

getComponent(EntityObject, ComponentIdentifier)#

Parameters#

NameTypeDescription
ComponentIdentifierStringThe identifier of the component to retrieve from the entity. This is either the identifier of a built-in component (check the Script Components section) or a custom component created with a call to registerComponent()
EntityObjectEntity JS API ObjectThe EntityObject that was retrieved from a call to createEntity() or retrieved from an event

Return Value#

TypeValue
Component JS API ObjectAn object with the following fields, and additionally, all the fields as defined in the component
Component JS API Object#
NameTypeComponent JS API ObjectDescription
__type__StringREAD ONLY. This defines the type of object. Will be: "component".
dataJavaScript ObjectThis is the content of the component.

Code Example:

Get a specified component from an entity

let globals = {
  ready: false
};

const mySystem = server.registerSystem(0, 0);

mySystem.update = function() {
  if(globals.ready == false) {
    globals.ready = true;
    let entity = this.createEntity("entity", "minecraft:pig");
    let positionComponent = this.getComponent(entity, "minecraft:position");
    if (positionComponent != null) {
      positionComponent.data.x = 0;
      positionComponent.data.y = 0;
      positionComponent.data.z = 0;
    }
  }
};

applyComponentChanges(EntityObject, ComponentObject)#

Parameters#

NameTypeDescription
ComponentObjectComponent JS API ObjectThe component object retrieved from the entity that was returned by either createComponent() or getComponent()
EntityObjectEntity JS API ObjectThe entity object that we are applying the component changes to

Return Value#

TypeValue
BooleanThe component was successfully updated

Code Example:

Apply updates to an entity's component

let globals = {
  pig: null
};

const mySystem = server.registerSystem(0, 0);

mySystem.update = function() {
  if(globals.pig == null) {
    globals.pig = this.createEntity("entity", "minecraft:pig");
  }
  else {
    let positionComponent = this.getComponent(globals.pig, "minecraft:position");
    positionComponent.data.y += 0.1;
    this.applyComponentChanges(globals.pig, positionComponent);
  }
};

destroyComponent(EntityObject, ComponentIdentifier)#

Parameters#

NameTypeDescription
ComponentIdentifierStringThe identifier of the component to remove from the entity. This is either the identifier of a built-in component (check the Script Components section) or a custom component created with a call to registerComponent()
EntityObjectEntity JS API ObjectThe EntityObject that was retrieved from a call to createEntity() or retrieved from an event

Return Value#

TypeValue
BooleanThe component was successfully removed from the entity

Code Example:

Destroy an entity's component

let globals = {
  myEntity: null
};

const mySystem = server.registerSystem(0, 0);

mySystem.initialize = function() {
  this.registerComponent("myPack:myCustomComponent", { myString: "string", myNumber: 0, myBool: true, myArray: [1, 2, 3] });
};

mySystem.update = function() {
  if(globals.myEntity == null) {
    globals.myEntity = this.createEntity();
  }
  else {
    if(this.hasComponent(globals.myEntity, "myPack:myCustomComponent")) {
      this.destroyComponent(globals.myEntity, "myPack:myCustomComponent");
    }
    else {
      this.createComponent(globals.myEntity, "myPack:myCustomComponent");
    }
  }
};

Event Bindings#

These are the bindings used to handle events. For a list of events you can react to or trigger, check the Events section of this document.

registerEventData(EventIdentifier, EventData)#

Parameters#

NameTypeDescription
EventDataJavaScript ObjectThe JavaScript object with the correct fields and default values for the event
EventIdentifierStringThis is the identifier of the custom event we are registering. The namespace is required and can't be set to minecraft.

Return Value#

TypeValue
BooleanSuccessfully registered the event data

createEventData(EventIdentifier)#

Parameters#

NameTypeDescription
EventIdentifierStringThis is the identifier of the custom event we are registering. The namespace is required and can't be set to minecraft.

Return Value#

TypeValue
JavaScript ObjectThe object containing the event data

listenForEvent(EventIdentifier, CallbackObject)#

Parameters#

NameTypeDescription
CallbackObjectJavaScript ObjectThe JavaScript object that will get called whenever the event is broadcast
EventIdentifierStringThis is the identifier of the event to which we want to react. Can be the identifier of a built-in event or a custom one from script

Return Value#

TypeValue
BooleanSuccessfully registered to listen for the event

Code Example:

Register a callback for a specified event

const mySystem = client.registerSystem(0, 0);

mySystem.initialize = function() {
  this.listenForEvent("minecraft:client_entered_world", (eventData) => this.onClientEnteredWorld(eventData));
};

mySystem.onClientEnteredWorld = function(eventData) {
  let messageData = this.createEventData("minecraft:display_chat_event");
  messageData.data.message = "Player has entered the world";
  this.broadcastEvent("minecraft:display_chat_event", messageData);
};

broadcastEvent(EventIdentifier, EventData)#

Parameters#

NameTypeDescription
EventDataJavaScript ObjectThe data for the event. You can create a new JavaScript Object with the parameters you want to pass in to the listener and the engine will take care of delivering the data to them
EventIdentifierStringThis is the identifier of the event we want to react to. Can be the identifier of a built-in event or a custom one from script

Return Value#

TypeValue
BooleanSuccessfully broadcasted the event

Code Example:

Broadcasting an event

const mySystem = client.registerSystem(0, 0);

mySystem.initialize = function() {
  let eventData = this.createEventData("minecraft:display_chat_event");
  eventData.data.message = "Hello, World!";
  this.broadcastEvent("minecraft:display_chat_event", eventData);
};


Entity Queries#

Entity Queries are a way for you to filter for entities based on their components. Once you have registered a query, you can request all the entities that are captured by it. Entity Queries will only ever return entities that are currently active in the level. If your query extends into chunks that are not currently loaded, entities there will not be included in the query.

registerQuery()#

Allows you to register a query. A query will contain all entities that meet the filter requirement.
No filters are added by default when you register a query so it will capture all entities.

Return Value#

TypeValue
Query JS API ObjectAn object containing the ID of the query

Code Example:

Query Registration

const mySystem = server.registerSystem(0, 0);

mySystem.initialize = function() {
  let myQuery = this.registerQuery();
};

registerQuery(Component, ComponentField1, ComponentField2, ComponentField3)#

Allows you to register a query that will only show entities that have the given component and define which fields of that component will be used as a filter when getting the entities from the query. You can either provide just the component identifier, or the component identifier and the name of 3 properties on that component to be tested (If you do specify property names, you must specify 3).

Parameters#

NameTypeDefault ValueDescription
ComponentStringThis is the identifier of the component that will be used to filter entities when
ComponentField1String"x"This is the name of the first field of the component that we want to filter entities by. By default this is set to x.
ComponentField2String"y"This is the name of the second field of the component that we want to filter entities by. By default this is set to y.
ComponentField3String"z"This is the name of the third field of the component that we want to filter entities by. By default this is set to z.

Return Value#

TypeValue
Query JS API ObjectAn object containing the ID of the query

Code Example:

Query Registration

const mySystem = server.registerSystem(0, 0);

mySystem.initialize = function() {
  let spatialQuery = this.registerQuery("minecraft:position", "x", "y", "z");
};

addFilterToQuery(Query, ComponentIdentifier)#

Allows you to add filters to your query. The query will only contain entities that have all the components specified.
By default no filters are added. This will allow queries to capture all entities.

Parameters

NameTypeDescription
ComponentIdentifierStringThis is the identifier of the component that will be added to the filter list. Only entities that have that component will be listed in the query
QueryQuery JS API ObjectThe object containing the ID of the query that you want to apply the filter to

Code Example:

Adding a filter to a query

let globals = {
  simpleQuery: null
};
const mySystem = server.registerSystem(0, 0);

mySystem.initialize = function() {
  globals.simpleQuery = this.registerQuery();
};

mySystem.update = function() {
  globals.simpleQuery = this.registerQuery();
  this.addFilterToQuery(globals.simpleQuery, "minecraft:explode");  let explodingEntities = this.getEntitiesFromQuery(globals.simpleQuery);
  for(var entity in explodingEntities) {
    server.log(JSON.stringify(entity));
  }
};

getEntitiesFromQuery(Query)#

Allows you to fetch the entities captured by a query.

Parameters#

NameTypeDescription
QueryQuery JS API ObjectThis is the query you registered earlier using registerQuery()

Return Value#

TypeValue
ArrayAn array of EntityObjects representing the entities found within the query

Code Example:

Get a list of entities from a query

const mySystem = server.registerSystem(0, 0);

mySystem.update = function() {
  let simpleQuery = this.registerQuery();
  let allEntities = this.getEntitiesFromQuery(simpleQuery);
  for(var entity in allEntities) {
    server.log(JSON.stringify(entity));
  }
};

getEntitiesFromQuery(Query, ComponentField1_Min, ComponentField2_Min, ComponentField3_Min, ComponentField1_Max, ComponentField2_Max, ComponentField3_Max)#

Allows you to fetch the entities captured by a query that was created with a component filter built-in. The only entities that will be returned are those entities that have the component that was defined when the query was registered and that have a value in the three fields on that component that were defined in the query within the values specified in the call to getEntitiesFromQuery.

Parameters#

NameTypeDescription
ComponentField1_MaxDecimalThe maximum value that the first component field needs to be on an entity for that entity to be included in the query
ComponentField1_MinDecimalThe minimum value that the first component field needs to be on an entity for that entity to be included in the query
ComponentField2_MaxDecimalThe maximum value that the second component field needs to be on an entity for that entity to be included in the query
ComponentField2_MinDecimalThe minimum value that the second component field needs to be on an entity for that entity to be included in the query
ComponentField3_MaxDecimalThe maximum value that the third component field needs to be on an entity for that entity to be included in the query
ComponentField3_MinDecimalThe minimum value that the third component field needs to be on an entity for that entity to be included in the query
QueryQuery JS API ObjectThis is the query you created earlier using registerQuery(...)

Return Value#

TypeValue
ArrayAn array of EntityObjects representing the entities found within the query

Code Example:

Get a list of entities from a query

let globals = {
  spatialQuery: null
};

const mySystem = server.registerSystem(0, 0);

mySystem.initialize = function() {
  globals.spatialQuery = this.registerQuery("minecraft:position", "x", "y", "z");
};

mySystem.update = function() {
  let closeEntities = this.getEntitiesFromQuery(globals.spatialQuery, 0, 10, 0, 5, 0, 10);
  for(var entity in closeEntities) {
    server.log(JSON.stringify(entity));
  }
};

Block Bindings#

These functions define how you interact with blocks.

getBlock(Ticking Area, x, y, z)#

Allows you to get a block from the world when provided an x, y, and z position. The block must be within a ticking area.

Parameters#

NameTypeDescription
Ticking AreaTicking Area JS API ObjectThe ticking area the block is in
xIntegerThe x position of the block you want
yIntegerThe y position of the block you want
zIntegerThe z position of the block you want

Return Value#

TypeValue
object
null

getBlock(Ticking Area, PositionObject)#

Allows you to get a block from the world when provided a JavaScript object containing a position. The block must be within a ticking area.

Parameters#

NameTypeDescription
PositionObjectJavaScript ObjectA JavaScript object with the x, y, and z position of the block you want
Parameters#
NameTypeDescription
xIntegerThe x position
yIntegerThe y position
zIntegerThe z position

|
| Ticking Area | Ticking Area JS API Object | The ticking area the block is in
|

Return Value#

TypeValue
Block JS API ObjectAn object containing the block

getBlocks(Ticking Area, x min, y min, z min, x max, y max, z max)#

Allows you to get an array of blocks from the world when provided a minimum and maximum x, y, and z position. The blocks must be within a ticking area. This call can be slow if given a lot of blocks, and should be used infrequently.

Parameters#

NameTypeDescription
Ticking AreaTicking Area JS API ObjectThe ticking area the blocks are in
x maxIntegerThe maximum x position of the blocks you want
x minIntegerThe minimum x position of the blocks you want
y maxIntegerThe maximum y position of the blocks you want
y minIntegerThe minimum y position of the blocks you want
z maxIntegerThe maximum z position of the blocks you want
z minIntegerThe minimum z position of the blocks you want

Return Value#

TypeValue
array
null

getBlocks(Ticking Area, Minimum PositionObject, Maximum PositionObject)#

Allows you to get an array of blocks from the world when provided a minimum and maximum position. The blocks must be within a ticking area. This call can be slow if given a lot of blocks, and should be used infrequently.

Parameters#

NameTypeDescription
Maximum PositionObjectJavaScript ObjectA JavaScript object with the maximum x, y, and z position of the blocks you want
Parameters#
NameTypeDescription
xIntegerThe x position
yIntegerThe y position
zIntegerThe z position

|
| Minimum PositionObject | JavaScript Object | A JavaScript object with the minimum x, y, and z position of the blocks you want

Parameters#
NameTypeDescription
xIntegerThe x position
yIntegerThe y position
zIntegerThe z position

|
| Ticking Area | Ticking Area JS API Object | The ticking area the blocks are in
|

Return Value#

TypeValue
ArrayA 3D array of block objects. Indexs are the blocks positions relative to the min position given
null

Slash Commands#

executeCommand(Command, Callback)#

NameTypeDescription
CallbackJSON ObjectThe JavaScript object that will be called after the command executes
CommandStringThe slash command to run

Example

system.executeCommand("/fill ~ ~ ~ ~100 ~5 ~50 stone", (commandResultData) => this.commandCallback(commandResultData));

system.commandCallback = function (commandResultData) {
  let eventData = this.createEventData("minecraft:display_chat_event");
  if (eventData) {
    eventData.data.message = message;
    this.broadcastEvent("minecraft:display_chat_event", "Callback called! Command: " + commandResultData.command + " Data: " + JSON.stringify(commandResultData.data, null, "    ") );
  }
};


Script Components#

This is the documentation for the attributes, properties, and components available from the Minecraft Script Engine.
There are two kinds of components: server components and client components. We will go into a bit more detail on what they are in their respective sections below.
Components can be added, retrieved, updated, and removed from entities. They do not exist on their own. Currently only user-defined components can be added and removed from entities. A component must be in an entity in order to retrieve or update it.
Check the Script Engine Bindings section to see how to add, remove, retrieve, and update components. This section deals with the specific API of each component.

Level Components#

minecraft:ticking_areas#

minecraft:weather#

NameTypeDescription
do_weather_cycleBooleanThis is the world option that determines if the vanilla weather cycle will be used
lightning_levelDecimalA value between 0 and 1 that determines how much lightning and thunder there is
lightning_timeIntegerHow long, in ticks, it will lightning and thunder for
rain_levelDecimalA value between 0 and 1 that determains how heavy the rainfall is
rain_timeIntegerHow long, in ticks, it will rain for

Server Components#

As much as possible, the API of each component matches its JSON counterpart (with some differences noted).

minecraft:armor_container#

// This example will check the players helmet armor slot for a specific item after the player attacks an entity.
system.listenForEvent("minecraft:player_attacked_entity", function(eventData) {
    // Get the players armor container
    let playerArmor = system.getComponent(eventData.data.player, "minecraft:armor_container");
    // Get the players helmet
    let playerHelmet = playerArmor.data[0];
    // Destroy the attacked entity if the player has a gold helmet equipped
    if (playerHelmet.item == "minecraft:golden_helmet") {
        system.destroyEntity(eventData.data.attacked_entity);
    }
});

minecraft:attack#

NameTypeDefault ValueDescription
damageRange [a, b]Range of the random amount of damage the melee attack deals. A negative value can heal the entity instead of hurting it
NameTypeDefault ValueDescription
------------
range_maxDecimal0.0The maximum amount of damage the entity will deal
range_minDecimal0.0The minimum amount of damage the entity will deal

minecraft:container#

// This example will check if a block has a container.
let block; // check getBlock API on how to access a block
let has_container = system.hasComponent(block, "minecraft:container");
if (has_container === true) {
  let container = system.getComponent(block, "minecraft:container");
  // you can now use the container to read items.


minecraft:collision_box#

Sets the width and height of the Entity's collision box.

NameTypeDefault ValueDescription
heightDecimal1.0Height of the collision box in blocks. A negative value will be assumed to be 0.
widthDecimal1.0Width and Depth of the collision box in blocks. A negative value will be assumed to be 0.

minecraft:damage_sensor#

Defines what events to call when this entity is damaged by specific entities or items.

NameTypeDefault ValueDescription
triggersListList of triggers with the events to call when taking specific kinds of damage.
NameTypeDefault ValueDescription
------------
causeStringnoneType of damage that triggers the events.
damage_modifierDecimal0.0A modifier that adds to/removes from the base damage from the damage cause. It does not reduce damage to less than 0.
damage_multiplierDecimal1.0A multiplier that modifies the base damage from the damage cause. If deals_damage is true the multiplier can only reduce the damage the entity will take to a minimum of 1.
deals_damageBooleantrueIf true, the damage dealt to the entity will take away health from it, set to false to make the entity ignore that damage.
on_damageJSON ObjectSpecifies filters for entity definitions and events.
on_damage_sound_eventStringDefines what sound to play, if any, when the on_damage filters are met.
// This example will cause an entity (in this case, a creeper) to start exploding when the player attacks it.
// Note: the entity must have the damage_sensor component and the associated events defined in their JSON description.
this.listenForEvent("minecraft:player_attacked_entity", function(eventData) {
  let damageSensorComponent = serverSystem.getComponent(eventData.attacked_entity, "minecraft:damage_sensor");
  damageSensorComponent.data[0].on_damage = { event:"minecraft:start_exploding", filters:[{test:"has_component", operator:"==", value:"minecraft:breathable"}] };
  serverSystem.applyComponentChanges(eventData.attacked_entity, damageSensorComponent);
});

minecraft:equipment#

Sets the Equipment table to use for this Entity.

NameTypeDefault ValueDescription
slot_drop_chanceListA list of slots with the chance to drop an equipped item from that slot.
tableStringThe file path to the equipment table, relative to the behavior pack's root.

minecraft:equippable#

Defines an entity's behavior for having items equipped to it.

slots#

List of slots and the item that can be equipped.

NameTypeDefault ValueDescription
accepted_itemsListThe list of items that can go in this slot.
interact_textStringText to be displayed when the entity can be equipped with this item when playing with Touch-screen controls.
itemStringIdentifier of the item that can be equipped for this slot.
on_equipStringEvent to trigger when this entity is equipped with this item.
on_unequipStringEvent to trigger when this item is removed from this entity.
slotInteger0The slot number of this slot.

minecraft:explode#

Defines how the entity explodes.

NameTypeDefault ValueDescription
breaks_blocksBooleantrueIf true, the explosion will destroy blocks in the explosion radius.
causes_fireBooleanfalseIf true, blocks in the explosion radius will be set on fire.
destroy_affected_by_griefingBooleanfalseIf true, whether the explosion breaks blocks is affected by the mob griefing game rule.
fire_affected_by_griefingBooleanfalseIf true, whether the explosion causes fire is affected by the mob griefing game rule.
fuse_lengthRange [a, b][0.0, 0.0]The range for the random amount of time the fuse will be lit before exploding, a negative value means the explosion will be immediate.
fuse_litBooleanfalseIf true, the fuse is already lit when this component is added to the entity.
max_resistanceDecimal3.40282e+38A blocks explosion resistance will be capped at this value when an explosion occurs.
powerDecimal3The radius of the explosion in blocks and the amount of damage the explosion deals.

minecraft:hand_container#

// This example will check the players offhand slot for a specific item after the player attacks an entity.
system.listenForEvent("minecraft:player_attacked_entity", function(eventData) {
    // Get the players hand container
    let handContainer = system.getComponent(eventData.data.player, "minecraft:hand_container");
    // Get the players offhand item
    let offhandItem = handContainer.data[1];
    // Destroy the attacked entity if the player has a totem in their offhand
    if (offhandItem.item == "minecraft:totem") {
        system.destroyEntity(eventData.data.attacked_entity);
    }
});

minecraft:healable#

Defines the interactions with this entity for healing it.

NameTypeDefault ValueDescription
filtersMinecraft FilterThe filter group that defines the conditions for using this item to heal the entity.
force_useBooleanfalseDetermines if item can be used regardless of entity being at full health.
itemsArrayThe array of items that can be used to heal this entity.
NameTypeDefault ValueDescription
------------
heal_amountInteger1The amount of health this entity gains when fed this item.
itemStringItem identifier that can be used to heal this entity.

|

minecraft:health#

NameTypeDefault ValueDescription
maxInteger10The maximum health the entity can heal
valueInteger1Current health of the entity

minecraft:hotbar_container#

// This example will check the players first hotbar item slot for a specific item after the player attacks an entity.
system.listenForEvent("minecraft:player_attacked_entity", function(eventData) {
    // Get the players hotbar
    let playerHotbar = system.getComponent(eventData.data.player, "minecraft:hotbar_container");
    // Get the item at the first slot in the hotbar
    let firstHotbarSlot = playerHotbar.data[0];
    // Destroy the attacked entity if the player has an apple in their first hotbar slot
    if (firstHotbarSlot.item == "minecraft:apple") {
        system.destroyEntity(eventData.data.attacked_entity);
    }
});

minecraft:interact#

NameTypeDefault ValueDescription
add_itemsJSON ObjectLoot table with items to add to the player's inventory upon successful interaction
NameTypeDefault ValueDescription
------------
tableStringFile path, relative to the behavior pack's path, to the loot table file
cooldownDecimal0.0Time in seconds before this entity can be interacted with again
hurt_itemInteger0The amount of damage the item will take when used to interact with this entity. A value of 0 means the item won't lose durability
interact_textStringText to show when the player is able to interact in this way with this entity when playing with Touch-screen controls
on_interactStringAn event identifier to fire when the interaction occurs
particle_on_startJSON ObjectParticle effect that will be triggered at the start of the interaction
NameTypeDefault ValueDescription
particle_offset_towards_interactorBooleanfalseWhether or not the particle will appear closer to who performed the interaction
particle_typeStringThe type of particle that will be spawned
particle_y_offsetDecimal0.0Will offset the particle this amount in the y direction
play_soundsArrayAn array of sound identifiers to play when the interaction occurs
spawn_entitiesArrayAn array of entity identifiers to spawn when the interaction occurs
spawn_itemsJSON ObjectLoot table with items to drop on the ground upon successful interaction
NameTypeDefault ValueDescription
------------
tableStringFile path, relative to the behavior pack's path, to the loot table file
swingBooleanfalseIf true, the player will do the 'swing' animation when interacting with this entity
transform_to_itemStringThe item used will transform to this item upon successful interaction. Format: itemName:auxValue
use_itemBooleanfalseIf true, the interaction will use an item

minecraft:inventory#

NameTypeDefault ValueDescription
additional_slots_per_strengthInteger0Number of slots that this entity can gain per extra strength
can_be_siphoned_fromBooleanfalseIf true, the contents of this inventory can be removed by a hopper
container_typeStringnoneType of container this entity has. Can be horse, minecart_chest, minecart_hopper, inventory, container or hopper
inventory_sizeInteger5Number of slots the container has
privateBooleanfalseIf true, only the entity can access the inventory
restrict_to_ownerBooleanfalseIf true, the entity's inventory can only be accessed by its owner or itself

minecraft:inventory_container#

// This example will check the players third inventory item slot for a specific item after the player attacks an entity.
system.listenForEvent("minecraft:player_attacked_entity", function(eventData) {
    // Get the players inventory
    let playerInventory = system.getComponent(eventData.data.player, "minecraft:inventory_container");
    // Get the item at the third slot in the inventory
    let thirdItemSlot = playerInventory.data[2];
    // Destroy the attacked entity if the player has an apple in their third item slot
    if (thirdItemSlot.item == "minecraft:apple") {
        system.destroyEntity(eventData.data.attacked_entity);
    }
});

minecraft:lookat#

Defines the behavior when another entity looks at this entity.

NameTypeDefault ValueDescription
allow_invulnerableBooleanfalseIf true, invulnerable entities (e.g. Players in creative mode) are considered valid targets.
filtersMinecraft FilterDefines the entities that can trigger this component.
look_cooldownRange [a, b][0, 0]The range for the random amount of time during which the entity is 'cooling down' and won't get angered or look for a target.
look_eventStringThe event identifier to run when the entities specified in filters look at this entity.
search_radiusDecimal10Maximum distance this entity will look for another entity looking at it.
set_targetBooleantrueIf true, this entity will set the attack target as the entity that looked at it.

minecraft:nameable#

NameTypeDefault ValueDescription
allow_name_tag_renamingBooleantrueIf true, this entity can be renamed with name tags
always_showBooleanfalseIf true, the name will always be shown
default_triggerStringTrigger to run when the entity gets named
nameStringThe current name of the entity, empty if the entity hasn't been named yet, making this non-empty will apply the name to the entity
name_actionsJSON ObjectDescribes the special names for this entity and the events to call when the entity acquires those names
NameTypeDefault ValueDescription
------------
name_filterListList of special names that will cause the events defined in 'on_named' to fire
on_namedStringEvent to be called when this entity acquires the name specified in 'name_filter'

minecraft:position#

NameTypeDefault ValueDescription
xDecimal0.0Position along the X-Axis (east-west) of the entity
yDecimal0.0Position along the Y-Axis (height) of the entity
zDecimal0.0Position along the Z-Axis (north-south) of the entity

minecraft:rotation#

NameTypeDefault ValueDescription
xDecimal0.0Controls the head rotation looking up and down
yDecimal0.0Controls the body rotation parallel to the floor

minecraft:shooter#

NameTypeDefault ValueDescription
auxValInteger-1ID of the Potion effect to be applied on hit
defStringEntity identifier to use as projectile for the ranged attack. The entity must have the projectile component to be able to be shot as a projectile

minecraft:spawn_entity#

Adds a timer after which this entity will spawn another entity or item (similar to vanilla's chicken's egg-laying behavior).

NameTypeDefault ValueDescription
filtersMinecraft FilterIf present, the specified entity will only spawn if the filter evaluates to true.
max_wait_timeInteger600Maximum amount of time to randomly wait in seconds before another entity is spawned.
min_wait_timeInteger300Minimum amount of time to randomly wait in seconds before another entity is spawned.
num_to_spawnInteger1The number of entities of this type to spawn each time that this triggers.
should_leashBooleanfalseIf true, this the spawned entity will be leashed to the parent.
single_useBooleanfalseIf true, this component will only ever spawn the specified entity once.
spawn_entityStringIdentifier of the entity to spawn, leave empty to spawn the item defined above instead.
spawn_eventStringminecraft:entity_bornEvent to call when the entity is spawned.
spawn_itemStringeggItem identifier of the item to spawn.
spawn_methodStringbornMethod to use to spawn the entity.
spawn_soundStringplopIdentifier of the sound effect to play when the entity is spawned.

minecraft:tag#

minecraft:teleport#

NameTypeDefault ValueDescription
dark_teleport_chanceDecimal0.01Modifies the chance that the entity will teleport if the entity is in darkness
light_teleport_chanceDecimal0.01Modifies the chance that the entity will teleport if the entity is in daylight
max_random_teleport_timeDecimal20Maximum amount of time in seconds between random teleports
min_random_teleport_timeDecimal0Minimum amount of time in seconds between random teleports
random_teleport_cubeVector [a, b, c][32, 16, 32]Entity will teleport to a random position within the area defined by this cube
random_teleportsBooleantrueIf true, the entity will teleport randomly
target_distanceDecimal16Maximum distance the entity will teleport when chasing a target
target_teleport_chanceDecimal1The chance that the entity will teleport between 0.0 and 1.0. 1.0 means 100%

minecraft:ticking_area_description#

NameTypeDefault ValueDescription
is_circleBooleanIs the area a circle. If false the area is a square.
maxVector [a, b, c](if area is a square) The edge of the area.
nameStringThe name of the area.
originVector [a, b, c]The origin position of the area.
radiusVector [a, b, c](if area is a circle) The radius of the area.

minecraft:tick_world#

NameTypeDescription
distance_to_playersDecimaldistance_to_players
never_despawnBooleanWhether or not this ticking area will despawn when a player is out of range
radiusIntegerThe radius in chunks of the ticking area
ticking_areaEntity Ticking Area JS API ObjectThe ticking area entity that is attached to this entity

minecraft:transformation#

NameTypeDefault ValueDescription
addJSON ObjectList of components to add to the entity after the transformation
NameTypeDefault ValueDescription
------------
component_groupsListNames of component groups to add
begin_transform_soundStringSound to play when the transformation starts
delayJSON ObjectDefines the properties of the delay for the transformation
NameTypeDefault ValueDescription
block_assist_chanceDecimal0.0Chance that the entity will look for nearby blocks that can speed up the transformation. Value must be between 0.0 and 1.0
block_chanceDecimal0.0Chance that, once a block is found, will help speed up the transformation
block_maxInteger0Maximum number of blocks the entity will look for to aid in the transformation. If not defined or set to 0, it will be set to the block radius
block_radiusInteger0Distance in Blocks that the entity will search for blocks that can help the transformation
block_typesListList of blocks that can help the transformation of this entity
keep_ownerBooleanIf this entity is owned by another entity, it should remain owned after transformation
valueDecimal0.0Time in seconds before the entity transforms

|
| drop_equipment | Boolean | | Cause the entity to drop all equipment upon transformation
|
| into | String | | Entity Definition that this entity will transform into
|
| transformation_sound | String | | Sound to play when the entity is done transforming
|

Client Components#

minecraft:molang#

Code Example:

let molangComponent = this.createComponent(entity, "minecraft:molang"); 
molangComponent["variable.molangexample"] = 1.0; 
this.applyComponentChanges(molangComponent); 


Block Components#

minecraft:blockstate#

Code Example:

let blockstateComponent = this.getComponent(block, "minecraft:blockstate");
blockstateComponent.data.coral_color = "blue";
this.applyComponentChanges(block, blockstateComponent);


Script Events#

Here you can find the list of events that you can listen for and respond to in your scripts.

Client Events#

Listening Events#

minecraft:client_entered_world#

minecraft:hit_result_changed#

NameTypeDescription
entityEntity JS API ObjectThe entity that was hit or null if it fired when moving off of an entity
positionVector [a, b, c]The position of the entity that was hit or null if it fired when moving off an entity

Code Example:

Responding to hit_result_changed

const mySystem = client.registerSystem(0, 0);

mySystem.initialize = function() {
  this.listenForEvent("minecraft:hit_result_changed", (eventData) => this.onHitChanged(eventData));
};

mySystem.onHitChanged = function(eventData) {
  if(eventData.position != null) {
    let chatEvent = this.createEventData("minecraft:display_chat_event");
    chatEvent.data.message = "Hit at x:" + eventData.position.x + " y:" + eventData.position.y + " z:" + eventData.position.z;
    this.broadcastEvent("minecraft:display_chat_event", chatEvent);
  }
};

minecraft:hit_result_continuous#

NameTypeDescription
entityEntity JS API ObjectThe entity that was hit or null if it not pointing at an entity
positionVector [a, b, c]The position of the entity that was hit or block that was hit

Code Example:

Responding to hit_result_continuous

const mySystem = client.registerSystem(0, 0);

mySystem.initialize = function() {
  this.listenForEvent("minecraft:hit_result_continuous", (eventData) => this.onHit(eventData));
};

mySystem.onHit = function(eventData) {
  if(eventData.position != null) {
    let chatEvent = this.createEventData("minecraft:display_chat_event");
    chatEvent.data.message = "Position at x:" + eventData.position.x + " y:" + eventData.position.y + " z:" + eventData.position.z;
    this.broadcastEvent("minecraft:display_chat_event", chatEvent);
  }
};

minecraft:pick_hit_result_changed#

NameTypeDescription
entityEntity JS API ObjectThe entity that was hit or null if it fired when moving off of an entity
positionVector [a, b, c]The position of the entity that was hit or null if it fired when moving off an entity

Code Example:

Responding to pick_hit_result_changed

const mySystem = client.registerSystem(0, 0);

mySystem.initialize = function() {
  this.listenForEvent("minecraft:pick_hit_result_changed", (eventData) => this.onPickChanged(eventData));
};

mySystem.onPickChanged = function(eventData) {
  if(eventData.position != null) {
    let chatEvent = this.createEventData("minecraft:display_chat_event");
    chatEvent.data.message = "Pick at x:" + eventData.position.x + " y:" + eventData.position.y + " z:" + eventData.position.z;
    this.broadcastEvent("minecraft:display_chat_event", chatEvent);
  }
};

minecraft:pick_hit_result_continuous#

NameTypeDescription
entityEntity JS API ObjectThe entity that was hit or null if it not pointing at an entity
positionVector [a, b, c]The position of the entity that was hit or block that was hit

Code Example:

Responding to pick_hit_result_continuous

const mySystem = client.registerSystem(0, 0);

mySystem.initialize = function() {
  this.listenForEvent("minecraft:pick_hit_result_continuous", (eventData) => this.onPick(eventData));
};

mySystem.onPick = function(eventData) {
  if(eventData.position != null) {
    let chatEvent = this.createEventData("minecraft:display_chat_event");
    chatEvent.data.message = "Pick at:" + eventData.position.x + " y:" + eventData.position.y + " z:" + eventData.position.y + " z:" + eventData.position.z;
    this.broadcastEvent("minecraft:display_chat_event", chatEvent);
  }
};

Trigger-able Events#

minecraft:display_chat_event#

NameTypeDefault ValueDescription
messageStringThe chat message that will be displayed

Code Example:

Trigger chat event

const mySystem = server.registerSystem(0, 0);

mySystem.update = function() {
  let chatEvent = this.createEventData("minecraft:display_chat_event");
  chatEvent.data.message = "Hello, World!";
  this.broadcastEvent("minecraft:display_chat_event", chatEvent);
};

minecraft:load_ui#

Event Data Parameters

NameTypeDefault ValueDescription
optionsJSON ObjectYou can define the following options for the screen by setting their value to true or false:
absorbs_input#

If true, input will not be passed down to any other screens underneath

always_accepts_input#

If true, the screen will always accept and process input for as long as it is in the stack, even if other custom UI screens appear on top of it

force_render_below#

If true, this screen will be rendered even if another screen is on top of it and will render over them, including the HUD

is_showing_menu#

If true, the screen will be treated as the pause menu and the pause menu won't be allowed to show on top of this screen

render_game_behind#

If true, the game will continue to be rendered underneath this screen

render_only_when_topmost#

If true, this screen will only be rendered if it is the screen at the top of the stack

should_steal_mouse#

If true, the screen will capture the mouse pointer and limit its movement to the UI screen

|
| path | String | | The file path to the screen's HTML file
|

minecraft:send_ui_event#

Custom UI is based on HTML 5. Review the scripting demo for an example of a custom UI file.

NameTypeDescription
dataStringThe data for the UI event being triggered
eventIdentifierStringThe identifier of the UI event

minecraft:spawn_particle_attached_entity#

NameTypeDefault ValueDescription
effectStringThe identifier of the particle effect you want to attach to the entity. This is the same name you gave the effect in its JSON file
entityEntity JS API ObjectThe entity object you want to attach the effect to
offsetVector [a, b, c][0, 0, 0]The offset from the entity's "center" where you want to spawn the effect

minecraft:spawn_particle_in_world#

NameTypeDefault ValueDescription
effectStringThe identifier of the particle effect you want to attach to spawn. This is the same name you gave the effect in its JSON file
positionVector [a, b, c][0, 0, 0]The position in the world where you want to spawn the effect

minecraft:unload_ui#

minecraft:script_logger_config#

NameTypeDefault ValueDescription
log_errorsBooleanfalseSet to true to log any scripting errors that occur on the client
log_informationBooleanfalseSet to true to log any general scripting information that occurs on the client. This includes any logging done with client.log()
log_warningsBooleanfalseSet to true to log any scripting warnings that occur on the client

Server Events#

Listening Events#

minecraft:entity_attack#

NameTypeDescription
entityEntity JS API ObjectThe entity that attacked
targetEntity JS API ObjectThe entity that was targeted in the attack

minecraft:player_attacked_entity#

NameTypeDescription
attacked_entityEntity JS API ObjectThe entity that was attacked by the player
playerEntity JS API ObjectThe player that attacked an entity

minecraft:entity_acquired_item#

NameTypeDescription
acquired_amountIntegerThe total number of items acquired by the entity during this event
acquisition_methodStringThe way the entity acquired the item
entityEntity JS API ObjectThe entity who acquired the item
item_stackItemStack JS API ObjectThe item that was acquired
secondary_entityEntity JS API ObjectIf it exists, the entity that affected the item before it was acquired. Example: A player completes a trade with a villager. The entity property would be the player and the secondary\_entity would be the villager

minecraft:entity_carried_item_changed#

NameTypeDescription
carried_itemItemStack JS API ObjectThe item that is now in the entities hands
entityEntity JS API ObjectThe entity that changed what they were carrying
handStringDefines which hand the item was equipped to. Either main or offhand.
previous_carried_itemItemStack JS API ObjectThe item that was previously in the entities hands

minecraft:entity_created#

NameTypeDescription
entityEntity JS API ObjectThe entity that was just created

minecraft:entity_definition_event#

NameTypeDescription
entityEntity JS API ObjectThe entity that was affected
eventStringThe event that was triggered

minecraft:entity_death#

NameTypeDescription
block_positionJavaScript ObjectThe position of the block that killed the entity
causeStringThe cause of the entity's death
entityEntity JS API ObjectThe entity that died
killerEntity JS API ObjectThe entity that killed the entity
projectile_typeStringThe type of the projectile that killed the entity

minecraft:entity_dropped_item#

NameTypeDescription
entityEntity JS API ObjectThe entity who dropped the item
item_stackItemStack JS API ObjectThe item that was dropped

minecraft:entity_equipped_armor#

NameTypeDescription
entityEntity JS API ObjectThe entity who is equipping the armor
item_stackItemStack JS API ObjectThe armor that is being equipped
slotStringDefines which slot the item was equipped to.

minecraft:entity_hurt#

NameTypeDescription
absorbed_damageIntegerThe amount the damage was reduced by by the entity's absorption effect
attackerEntity JS API ObjectPresent only when damaged by an entity or projectile. The entity that attacked and caused the damage
block_positionVector [a, b, c]Present only when damaged by a block. This is the position of the block that hit the entity
causeStringThe way the entity took damage. Refer to the Damage Source documentation for a complete list of sources
damageIntegerThe amount of damage the entity took after immunity and armor are taken into account
entityEntity JS API ObjectThe entity that took damage
projectile_typeStringPresent only when damaged by a projectile. This is the identifier of the projectile that hit the entity

minecraft:entity_move#

NameTypeDescription
entityEntity JS API ObjectThe entity that moved

minecraft:entity_sneak#

NameTypeDescription
entityEntity JS API ObjectThe entity that changed their sneaking state
sneakingBooleanIf true, the entity just started sneaking. If false, the entity just stopped sneaking

minecraft:entity_start_riding#

NameTypeDescription
entityEntity JS API ObjectThe rider
rideEntity JS API ObjectThe entity being ridden

minecraft:entity_stop_riding#

NameTypeDescription
entityEntity JS API ObjectThe entity that was riding another entity
entity_is_being_destroyedBooleanIf true, the rider stopped riding because they are now dead
exit_from_riderBooleanIf true, the rider stopped riding by their own decision
switching_ridesBooleanIf true, the rider stopped riding because they are now riding a different entity

minecraft:entity_tick#

NameTypeDescription
entityEntity JS API ObjectThe entity that was ticked

minecraft:entity_use_item#

NameTypeDescription
entityEntity JS API ObjectThe entity who is using the item
item_stackItemStack JS API ObjectThe item that is being used
use_methodStringThe way the entity used the item

minecraft:block_destruction_started#

NameTypeDescription
block_positionJavaScript ObjectThe position of the block that is being destroyed
playerEntity JS API ObjectThe player that started destoying the block

minecraft:block_destruction_stopped#

NameTypeDescription
block_positionJavaScript ObjectThe position of the block that was being destroyed
destruction_progressDecimalHow far along the destruction was before it was stopped (0 - 1 range)
playerEntity JS API ObjectThe player that stopped destoying the block

minecraft:block_exploded#

NameTypeDescription
block_identifierStringThe identifier of the block that was destroyed
block_positionJavaScript ObjectThe position of the block that was destroyed by the explosion
causeStringThe cause of the block's destruction
entityEntity JS API ObjectThe entity that exploded

minecraft:block_interacted_with#

NameTypeDescription
block_positionJavaScript ObjectThe position of the block that is being interacted with
playerEntity JS API ObjectThe player that interacted with the block

minecraft:piston_moved_block#

NameTypeDescription
block_positionJavaScript ObjectThe position of the block that was moved
piston_actionStringThe action the piston took, "extended" or "retracted"
piston_positionJavaScript ObjectThe position of the piston that moved the block

minecraft:player_destroyed_block#

NameTypeDescription
block_identifierStringThe identifier of the block that was destroyed
block_positionJavaScript ObjectThe position of the block that was destroyed
playerEntity JS API ObjectThe player that destroyed the block

minecraft:player_placed_block#

NameTypeDescription
block_positionJavaScript ObjectThe position of the block that was placed
playerEntity JS API ObjectThe player that placed the block

minecraft:play_sound#

NameTypeDefault ValueDescription
pitchDecimal1.0The pitch of the sound effect. A value of 1.0 will play the sound effect with regular pitch
positionVector [a, b, c][0, 0, 0]The position in the world we want to play the sound at
soundStringThe identifier of the sound you want to play. Only sounds defined in the applied resource packs can be played
volumeDecimal1.0The volume of the sound effect. A value of 1.0 will play the sound effect at the volume it was recorded at

minecraft:projectile_hit#

NameTypeDescription
entityEntity JS API ObjectThe entity that was hit by the projectile, if any
ownerEntity JS API ObjectThe entity that fired the projectile
positionVector [a, b, c]The position of the collision
projectileEntity JS API ObjectThe projectile in question

minecraft:weather_changed#

NameTypeDescription
dimensionStringThe name of the dimension where the weather change happened
lightningBooleanTells if the new weather has lightning
rainingBooleanTells if the new weather has rain

Trigger-able Events#

minecraft:entity_definition_event#

NameTypeDefault ValueDescription
entityEntity JS API ObjectThe entity object you want to attach the effect to
eventStringThe identifier of the event to trigger on that entity. Both built-in (minecraft:) and custom events are supported

minecraft:display_chat_event#

NameTypeDefault ValueDescription
messageStringThe chat message that will be displayed

minecraft:execute_command#

NameTypeDefault ValueDescription
commandStringThe command that will be run

minecraft:play_sound#

NameTypeDefault ValueDescription
pitchDecimal1.0The pitch of the sound effect. A value of 1.0 will play the sound effect with regular pitch
positionVector [a, b, c][0, 0, 0]The position in the world we want to play the sound at
soundStringThe identifier of the sound you want to play. Only sounds defined in the applied resource packs can be played
volumeDecimal1.0The volume of the sound effect. A value of 1.0 will play the sound effect at the volume it was recorded at

minecraft:spawn_particle_attached_entity#

NameTypeDefault ValueDescription
effectStringThe identifier of the particle effect you want to attach to the entity. This is the same identifier you gave the effect in its JSON file
entityEntity JS API ObjectThe entity object you want to attach the effect to
offsetVector [a, b, c][0, 0, 0]The offset from the entity's "center" where you want to spawn the effect

minecraft:spawn_particle_in_world#

NameTypeDefault ValueDescription
dimensionStringoverworldThe dimension in which you want to spawn the effect. Can be "overworld", "nether", or "the end"
effectStringThe identifier of the particle effect you want to attach to spawn. This is the same name you gave the effect in its JSON file
positionVector [a, b, c][0, 0, 0]The position in the world where you want to spawn the effect

minecraft:script_logger_config#

NameTypeDefault ValueDescription
log_errorsBooleanfalseSet to true to log any scripting errors that occur on the server
log_informationBooleanfalseSet to true to log any general scripting information that occurs on the server. This includes any logging done with server.log()
log_warningsBooleanfalseSet to true to log any scripting warnings that occur on the server

Scripting System#

The Minecraft Script Engine uses the JavaScript language.
You can write JavaScript scripts and bundle them with Behavior Packs to listen and respond to game events, get and modify data in components that entities have, and affect different parts of the game.

Demos#

DemoLast UpdatedDownload Link
Mob Arena10/24/2018https://aka.ms/minecraftscripting_mobarena
Turn-Based RPG10/24/2018https://aka.ms/minecraftscripting_turnbased

Known Issues#

IssueWorkaround
Scripts are not loaded properly from archived packs
Custom UI doesn't work in VR or MR mode
Custom UI doesn't retain state upon suspend and resume
Exiting a world without scripts and entering one that has scripts might cause the wrong world to load
Calling removeEntity on a dying entity might cause the game to crash

Breaking Changes#

CategoryChange
UI
Components
Events
Events
Events
Events

Pre-Requisites#

NOTE: Scripts are only supported on Windows 10 PCs at the moment. If you try to open a world with scripts on a device that doesn't support scripts, you will see an error message letting you know you can't enter the world.

SoftwareMinimumRecommended
Code EditorVisual Studio Code or any plain-text editorVisual Studio Community 2017 with the following components installed: 'JavaScript diagnostics', 'JavaScript and TypeScript language support', 'Just-In-Time debugger'
DebuggerN/AVisual Studio Community 2017
MinecraftMinecraft on your Windows 10 deviceMinecraft on your Windows 10 device
OtherVanilla Behavior Pack available from https://aka.ms/behaviorpacktemplateVanilla Behavior Pack available from https://aka.ms/behaviorpacktemplate
Storage1.0 GB of free space for text editor, game, and scripts3.0 GB of free space for Visual Studio, game, and scripts

Getting Started#

Once you have downloaded the Behavior Pack, unzip it to a folder. Inside the Behavior Pack you will find the scripts folder which contains all the scripting files you want to run.
In the scripts folder you will find two folders: one for client scripts and one for server scripts.
-Server Scripts: These scripts run on the server side of the game. This includes spawning new entities, adding components, or modifying components on an entity.
-Client Scripts: These scripts run on each individual player's side of the game. This is a good place to respond to events and manage anything specific to the player.
Once you have chosen whether you are making a client or server script, simply add a new blank text file with .js extension to the appropriate folder, and open it in your preferred code editor. Then code away! You can have as many or as few JavaScript files as you want here (the name of the files doesn't matter) and they will all be run independently of each other!

NOTE: For scripts to be run by the game, you need to enable Experimental Gameplay on the world where you will run scripts on. This will be necessary while scripting is still in beta.
When entering a world that has client scripts in it, you will be prompted to accept that you wish to run scripts on your device (this will show up both for local worlds as well as multiplayer worlds).
Additionally, if your pack contains client scripts, you need to include a client_data module in the pack's manifest. This tells the game anything in the scripts/client folder needs to be sent over to the clients. Please refer to the Add-on Documentation page for more information on the pack's manifest contents.

Folder Structure

Example of manifest module needed for client scripts

        {
            "description": "Example client scripts module",
            "type": "client_data",
            "uuid": "c05a992e-482a-455f-898c-58bbb4975e47",
            "version": [0, 0, 1]
        }


vanilla_behavior_pack

|-scripts
|--client
|---myClientScript.js
|--server
|---myServerScript.js
|-manifest.json
|-pack_icon.png

Structure of a Script#

These are, in a way, the required parts of a script but they are by no means the only parts you can have. You can create additional methods as needed - just make sure they are called from somewhere in one of the methods below!

1. System Registration#

NameTypeDescription
majorVersionIntegerThis is the major version of the Minecraft Script Engine your script was designed to work with
minorVersionIntegerThis is the revision of the Minecraft Script Engine your script was designed to work with

Code Examples:

Client System

let sampleClientSystem = client.registerSystem(0, 0);

Server System

let sampleServerSystem = server.registerSystem(0, 0);

2. System Initialization#

You can use this to set up the environment for your script: register custom components and events, sign up event listeners, etc. This will run BEFORE the world is ready and the player has been added to it. This function should be used to initialize variables and setup event listeners. You shouldn't try to spawn or interact with any entities at this point! You should also avoid interaction with UI elements or sending messages to the chat window since this is called before the player is ready.

Code Example:

sampleSystem.initialize = function() {
  //register event data, register components, register queries, listen for events
};

3. System Update#

Code Example:

sampleSystem.update = function() {
  //Update all the things
};

4. System Shutdown#

Code Example:

sampleSystem.shutdown = function() {
  //Cleanup script only things
};

Debugging#

There are two ways to tell what happened when something goes wrong with a script: in-game and advanced, which we will describe below. You only need the game and your script to debug in-game, but you will need a Windows 10 PC and Visual Studio installed for the advanced debugging.

In-Game#

We strongly encourage you to build further debug messages and tools into your scripts while working on them. This will help you discern when something isn't working quite right. Reach out on the official Discord channel if you need additional help: https://discord.gg/Minecraft

Real-Time (Advanced)#

If you installed Visual Studio with the components mentioned in the "Recommended" section of this document you will have installed and enabled the Just-In-Time Debugger. This tool will pop-up a message from Visual Studio whenever an exception occurs in your script and allow you to open Visual Studio on the line of your script that broke.

Additionally, you can connect to the Script Engine manually and debug your code. You can use remote debugging to connect and debug Minecraft running on another device. Please refer to the Visual Studio Debugger documentation above for instructions on how to use remote debugging.
First you need to start up Visual Studio. If this is the first time you have launched Visual Studio after installation, we suggest setting up your environment for JavaScript development and logging in to your Microsoft account when prompted. This will set up the Visual Studio interface with the most important tools you will need.
Once you have Visual Studio open you should launch Minecraft. Then create a new world with Experimental Gameplay enabled and apply the Behavior Pack containing your scripts.
After creating the world go back to Visual Studio and click on the Debug menu. Then click on "Attach to Process". In the window that opens there will be a search box titled Filter Process. Click on it and type Minecraft.
Once the list is narrowed down to only the instance of Minecraft running, you can verify that the Script Engine is running by looking at the Type column. This will say Script and either x86 or x64.

Select the process and click on Attach to attach the debugger to the game. Now you will be able to press the Pause button to pause the Script Engine when the next line of script code runs. This allows you to inspect the values of variables in your script and break into Visual Studio if an error occurs in your code.
WARNING: When you hit a breakpoint to step through code with a debugger, it is possible for a client to time out and disconnect or for the server to disconnect all players.

User-Defined Components#

User-Defined components are a special kind of component that can be defined in script and no built-in game system acts on it.
The component needs to be registered with the Script Engine by giving it a name and a set of fields in the format name:value. Once applied, the component behaves like any of the built-in components: you can get it from an entity, modify its values, and apply the changes.
Currently User-Defined components are the only components that can be dynamically added and removed from an entity using scripts. They don't need to be previously defined in an entity's JSON file. In the current version these components will NOT be saved out or loaded back in: they only exist while the entity is there and need to be added back when reloading the level.

Code Example:

Component Registration

this.registerComponent("myNamespace:myComponent", { myString: "TamerJe