Private
constructorReadonly
afterContains a set of events that are applicable to the entirety of the world. Event callbacks are called in a deferred manner. Event callbacks are executed in read-write mode.
import { world } from "@minecraft/server";
const callback = world.afterEvents.itemUseOn.subscribe((event) => {
if (event.itemStack.typeId == "minecraft:water_bucket") {
event.source.sendMessage("You used water bucket once.");
// Unsubscribe callback after first use
world.afterEvents.itemUseOn.unsubscribe(callback);
}
});
Readonly
beforeContains a set of events that are applicable to the entirety of the world. Event callbacks are called immediately. Event callbacks are executed in read-only mode.
// Check out how BeforeEvents privilege system work:
// https://wiki.bedrock.dev/scripting/script-server.html#beforeevents-privilege-system
import { world, system, TimeOfDay } from "@minecraft/server";
// Use system.run()
world.beforeEvents.chatSend.subscribe((event) => {
event.cancel = true;
// setTime changes world state, must be run after its execution by a tick
system.run(() => {
world.setTimeOfDay(TimeOfDay.Night);
});
});
/**
* @param {number} ticks
*/
function sleep(ticks) {
return new Promise((resolve) => {
system.runTimeout(() => resolve(), ticks);
});
}
// Or execute function at a later tick using async functions
world.beforeEvents.chatSend.subscribe(async (event) => {
// synchronous code
event.cancel = true;
// asynchronous code
await sleep(10); // Pretend you have a sleep function that returns a promise that resolves in 10 ticks
world.setTimeOfDay(TimeOfDay.Night);
});
import { system, world } from "@minecraft/server";
const callback = world.beforeEvents.itemUseOn.subscribe((event) => {
if (event.itemStack.typeId == "minecraft:water_bucket") {
event.source.sendMessage(
"You cannot use water bucket at this time, please try again."
);
event.cancel = true;
// Unsubscribe callback after first use
system.run(() => world.beforeEvents.itemUseOn.unsubscribe(callback));
}
});
Readonly
gameThe game rules that apply to the world.
import { world } from "@minecraft/server";
world.gameRules.doDayLightCycle = false;
world.gameRules.doEntityDrops = false;
world.gameRules.doFireTick = false;
world.gameRules.doWeatherCycle = false;
world.gameRules.doMobSpawning = false;
Readonly
is// Script by WavePlayz
import { world } from "@minecraft/server";
// Subscribe to the `playerSpawn` event, which is triggered when the world is initialized
world.afterEvents.playerSpawn.subscribe(() => {
// Check if the world is in hardcore mode
// Notify players about the current mode
if (world.isHardcore) {
world.sendMessage(
"Welcome to Hardcore mode! Be careful, as death is permanent."
);
} else {
world.sendMessage("This world is not in Hardcore mode. Play safely!");
}
});
Readonly
scoreboardReturns the general global scoreboard that applies to the world.
import { world } from "@minecraft/server";
const money = world.scoreboard.getObjective("money");
Readonly
structureReturns the manager for Structure related APIs.
import { world } from "@minecraft/server";
world.structureManager.getWorldStructureIds().forEach((id) => {
const structure = world.structureManager.get(id);
structure.isValid();
});
Returns an array of all active players within the world.
This function can throw errors.
import { EntityHealthComponent, system, world } from "@minecraft/server";
system.runInterval(() => {
for (const player of world.getPlayers()) {
const health = player.getComponent(EntityHealthComponent.componentId);
player.onScreenDisplay.setActionBar(
`Name: ${
player.name
} | Health: ${health.currentValue.toFixed()} / ${
health.effectiveMax
}`
);
}
}, 5000);
The default Overworld spawn location. By default, the Y coordinate is 32767, indicating a player's spawn height is not fixed and will be determined by surrounding blocks.
Returns the default Overworld spawn location.
import { world } from "@minecraft/server";
const spawnLocation = world.getDefaultSpawnLocation();
world.sendMessage(
`Spawn location: ${spawnLocation.x}, ${spawnLocation.y}, ${spawnLocation.z}`
);
The name of the dimension. For example, "overworld", "nether" or "the_end".
The requested dimension
Returns a dimension object.
Throws if the given dimension name is invalid
import { world } from "@minecraft/server";
world.getDimension("nether");
import { world } from "@minecraft/server";
world.getDimension("overworld");
import { world } from "@minecraft/server";
world.getDimension("the_end");
The property identifier.
Returns the value for the property, or undefined if the property has not been set.
Returns a property value.
Throws if the given dynamic property identifier is not defined.
import * as mc from '@minecraft/server';
function incrementProperty(propertyName: string): boolean {
let number = mc.world.getDynamicProperty(propertyName);
console.warn('Current value is: ' + number);
if (number === undefined) {
number = 0;
}
if (typeof number !== 'number') {
console.warn('Number is of an unexpected type.');
return false;
}
mc.world.setDynamicProperty(propertyName, number + 1);
return true;
}
incrementProperty('samplelibrary:number');
import * as mc from '@minecraft/server';
function updateWorldProperty(propertyName: string): boolean {
let paintStr = mc.world.getDynamicProperty(propertyName);
let paint: { color: string; intensity: number } | undefined = undefined;
console.log('Current value is: ' + paintStr);
if (paintStr === undefined) {
paint = {
color: 'purple',
intensity: 0,
};
} else {
if (typeof paintStr !== 'string') {
console.warn('Paint is of an unexpected type.');
return false;
}
try {
paint = JSON.parse(paintStr);
} catch (e) {
console.warn('Error parsing serialized struct.');
return false;
}
}
if (!paint) {
console.warn('Error parsing serialized struct.');
return false;
}
paint.intensity++;
paintStr = JSON.stringify(paint); // be very careful to ensure your serialized JSON str cannot exceed limits
mc.world.setDynamicProperty(propertyName, paintStr);
return true;
}
updateWorldProperty('samplelibrary:longerjson');
// Script by WavePlayz
import { world } from "@minecraft/server";
// Subscribe to the `playerJoin` event, which is triggered when a player joins the world
world.afterEvents.playerJoin.subscribe((eventData) => {
// Extract the player entity from the event data
const player = eventData.player;
// Attempt to retrieve a custom dynamic property
const playersCount = world.getDynamicProperty("playersCount");
// If the property doesn't exist
playersCount ??= 0;
// set a default value
player.setDynamicProperty("playersCount", playersCount + 1);
});
A string array of active dynamic property identifiers.
Gets a set of dynamic property identifiers that have been set in this world.
import { world } from "@minecraft/server";
world.getDynamicPropertyIds().forEach((id) => {
const value = world.getDynamicProperty(id)!;
world.sendMessage(`Dynamic property ${id} has value ${value}`);
});
world.sendMessage(
"There are " + world.getDynamicPropertyIds().length + " dynamic properties"
);
Gets the total byte count of dynamic properties. This could potentially be used for your own analytics to ensure you're not storing gigantic sets of dynamic properties.
import { world } from "@minecraft/server";
world.getDynamicPropertyTotalByteCount();
The id of the entity.
The requested entity object.
Returns an entity based on the provided id.
Throws if the given entity id is invalid.
import { world } from "@minecraft/server";
// Entity::id - format: '-451021564564561'
const entityId = world
.getDimension("overworld")
.spawnEntity(
"minecraft:npc",
{ x: 0, y: 70, z: 0 },
{ initialPersistence: true }
).id;
world.getEntity(entityId).typeId; // minecraft:npc
Returns the MoonPhase for the current time.
import { MoonPhase, world } from "@minecraft/server";
// Get the current moon phase
const moonPhase: MoonPhase = world.getMoonPhase();
// Display a message based on the current moon phase
switch (moonPhase) {
case MoonPhase.FullMoon:
world.sendMessage("It's full moon!");
break;
case MoonPhase.WaningGibbous:
world.sendMessage("It's waning gibbous moon!");
break;
// Add cases for other moon phases as needed
default:
world.sendMessage("It's another phase of the moon.");
}
Optional
options: EntityQueryOptionsAdditional options that can be used to filter the set of players returned.
Optional
A player array.
Returns a set of players based on a set of conditions defined via the EntityQueryOptions set of filter criteria.
Throws if the provided EntityQueryOptions are invalid.
import { world } from "@minecraft/server";
world.getPlayers({ families: ["player"] });
import { EntityQueryOptions, world } from "@minecraft/server";
const entityQueryOptions: EntityQueryOptions = {
minLevel: 10,
maxLevel: 30,
tags: ["team_red"],
excludeNames: ["Admin"],
};
const filteredPlayers = world.getPlayers(entityQueryOptions);
console.log(
"Filtered Players:",
filteredPlayers.map((player) => player.name)
);
The time of day, in ticks, between 0 and 24000.
Returns the time of day.
import { TimeOfDay, system, world } from "@minecraft/server";
function GetWorldTime() {
const daytime = world.getTimeOfDay() + 6000;
const datetime = new Date(daytime * 3.6 * 1000);
const hours =
datetime.getHours() < 10
? "0" + datetime.getHours()
: datetime.getHours();
const minutes =
datetime.getMinutes() < 10
? "0" + datetime.getMinutes()
: datetime.getMinutes();
return { hours, minutes };
}
system.runInterval(() => {
const { hours, minutes } = GetWorldTime();
for (const player of world.getAllPlayers()) {
player.onScreenDisplay.setActionBar(`Time - ${hours}:${minutes}`);
}
});
Optional
musicOptions: MusicOptionsOptional
Plays a particular music track for all players.
This function can't be called in read-only mode.
This function can throw errors.
import { world, MusicOptions, WorldSoundOptions, PlayerSoundOptions, Vector3 } from '@minecraft/server';
import { MinecraftDimensionTypes } from '@minecraft/vanilla-data';
const players = world.getPlayers();
const targetLocation: Vector3 = {
x: 0,
y: 0,
z: 0,
};
const musicOptions: MusicOptions = {
fade: 0.5,
loop: true,
volume: 1.0,
};
world.playMusic('music.menu', musicOptions);
const worldSoundOptions: WorldSoundOptions = {
pitch: 0.5,
volume: 4.0,
};
const overworld = world.getDimension(MinecraftDimensionTypes.Overworld);
overworld.playSound('ambient.weather.thunder', targetLocation, worldSoundOptions);
const playerSoundOptions: PlayerSoundOptions = {
pitch: 1.0,
volume: 1.0,
};
players[0].playSound('bucket.fill_water', playerSoundOptions);
// Script by WavePlayz
import { world } from "@minecraft/server";
// Subscribe to the `playerJoin` event, which is triggered when a player joins the world
world.afterEvents.playerJoin.subscribe((eventData) => {
const player = eventData.player;
// Play a music track for the player when they join the world
player.playMusic("minecraft:music.game", {
volume: 1.0, // Volume level of the music (1.0 is normal)
fade: 0.5, // Fade in/out time in seconds
});
player.sendMessage("Welcome! Enjoy the music while you play.");
});
Optional
soundOptions: WorldSoundOptionsOptional
Plays a sound for all players. DEPRECATED: Use Dimension.playSound.
This function can't be called in read-only mode.
An error will be thrown if volume is less than 0.0. An error will be thrown if fade is less than 0.0. An error will be thrown if pitch is less than 0.01. An error will be thrown if volume is less than 0.0.
import { world, MusicOptions, WorldSoundOptions, PlayerSoundOptions, Vector3 } from '@minecraft/server';
import { MinecraftDimensionTypes } from '@minecraft/vanilla-data';
const players = world.getPlayers();
const targetLocation: Vector3 = {
x: 0,
y: 0,
z: 0,
};
const musicOptions: MusicOptions = {
fade: 0.5,
loop: true,
volume: 1.0,
};
world.playMusic('music.menu', musicOptions);
const worldSoundOptions: WorldSoundOptions = {
pitch: 0.5,
volume: 4.0,
};
const overworld = world.getDimension(MinecraftDimensionTypes.Overworld);
overworld.playSound('ambient.weather.thunder', targetLocation, worldSoundOptions);
const playerSoundOptions: PlayerSoundOptions = {
pitch: 1.0,
volume: 1.0,
};
players[0].playSound('bucket.fill_water', playerSoundOptions);
// Script by WavePlayz
import { world } from "@minecraft/server";
// Subscribe to the `playerUseItemOn` event, which is triggered when a player uses an item on a block
world.afterEvents.playerUseItemOn.subscribe((eventData) => {
const player = eventData.source;
// Play a sound effect when the player uses an item on a block
player.playSound("minecraft:block.anvil.use", {
volume: 0.8, // Volume level of the sound (1.0 is normal)
pitch: 1.2, // Pitch of the sound (1.0 is normal)
position: player.location, // Position where the sound should be played
});
player.sendMessage("You used an item on a block. Sound played!");
});
Identifier of the music track to play.
Optional
musicOptions: MusicOptionsAdditional options for the music track.
Optional
Queues an additional music track for players. If a track is not playing, a music track will play.
This function can't be called in read-only mode.
An error will be thrown if volume is less than 0.0. An error will be thrown if fade is less than 0.0.
import { world } from "@minecraft/server";
world.queueMusic("music.game.swamp_music", { loop: true });
The message to be displayed.
Sends a message to all players.
This method can throw if the provided RawMessage is
in an invalid format. For example, if an empty name
string
is provided to score
.
import { world } from '@minecraft/server';
// Displays "Apple or Coal"
const rawMessage = {
translate: 'accessibility.list.or.two',
with: { rawtext: [{ translate: 'item.apple.name' }, { translate: 'item.coal.name' }] },
};
world.sendMessage(rawMessage);
import { world } from '@minecraft/server';
// Displays the player's score for objective "obj". Each player will see their own score.
const rawMessage = { score: { name: '*', objective: 'obj' } };
world.sendMessage(rawMessage);
import { world } from '@minecraft/server';
// Displays "Hello, world!"
world.sendMessage('Hello, world!');
import { world } from '@minecraft/server';
// Displays "First or Second"
const rawMessage = { translate: 'accessibility.list.or.two', with: ['First', 'Second'] };
world.sendMessage(rawMessage);
// Script by WavePlayz
import { world } from "@minecraft/server";
// Subscribe to the `playerSpawn` event, which is triggered when a player joins the world
world.afterEvents.playerSpawn.subscribe((eventData) => {
// ignore if player respawns
if (!eventData.initialSpawn) return;
const player = eventData.player;
// Construct a welcome message for the player who just joined
const welcomeMessage = `Welcome ${player.name}! Have fun in the world of Minecraft!`;
// Use world.sendMessage to broadcast the message to all players in the world
world.sendMessage(welcomeMessage);
// Notify the player specifically with a different message
player.sendMessage("Feel free to explore and build your adventure!");
});
Location of the spawn point. Note that this is assumed to be within the overworld dimension.
Sets a default spawn location for all players.
This function can't be called in read-only mode.
Throws if the provided spawn location is out of bounds.
Error
LocationOutOfWorldBoundariesError
import { world } from "@minecraft/server";
world.setDefaultSpawnLocation({
x: 0,
y: -64,
z: 0,
});
The property identifier.
Optional
value: string | number | boolean | Vector3Data value of the property to set.
Optional
Sets a specified property to a value.
Throws if the given dynamic property identifier is not defined.
import * as mc from '@minecraft/server';
function incrementProperty(propertyName: string): boolean {
let number = mc.world.getDynamicProperty(propertyName);
console.warn('Current value is: ' + number);
if (number === undefined) {
number = 0;
}
if (typeof number !== 'number') {
console.warn('Number is of an unexpected type.');
return false;
}
mc.world.setDynamicProperty(propertyName, number + 1);
return true;
}
incrementProperty('samplelibrary:number');
import * as mc from '@minecraft/server';
function updateWorldProperty(propertyName: string): boolean {
let paintStr = mc.world.getDynamicProperty(propertyName);
let paint: { color: string; intensity: number } | undefined = undefined;
console.log('Current value is: ' + paintStr);
if (paintStr === undefined) {
paint = {
color: 'purple',
intensity: 0,
};
} else {
if (typeof paintStr !== 'string') {
console.warn('Paint is of an unexpected type.');
return false;
}
try {
paint = JSON.parse(paintStr);
} catch (e) {
console.warn('Error parsing serialized struct.');
return false;
}
}
if (!paint) {
console.warn('Error parsing serialized struct.');
return false;
}
paint.intensity++;
paintStr = JSON.stringify(paint); // be very careful to ensure your serialized JSON str cannot exceed limits
mc.world.setDynamicProperty(propertyName, paintStr);
return true;
}
updateWorldProperty('samplelibrary:longerjson');
// Script by WavePlayz
import { world } from "@minecraft/server";
// Subscribe to the `playerJoin` event, which is triggered when a player joins the world
world.afterEvents.playerJoin.subscribe((eventData) => {
// Extract the player entity from the event data
const player = eventData.player;
// Attempt to retrieve a custom dynamic property
const playersCount = world.getDynamicProperty("playersCount");
// If the property doesn't exist
playersCount ??= 0;
// set a default value
player.setDynamicProperty("playersCount", playersCount + 1);
});
The time of day, in ticks, between 0 and 24000.
Sets the time of day.
This function can't be called in read-only mode.
Throws if the provided time of day is not within the valid range.
import { TimeOfDay, world } from "@minecraft/server";
world.setTimeOfDay(TimeOfDay.Day);
import { TimeOfDay, world } from "@minecraft/server";
world.setTimeOfDay(TimeOfDay.Midnight);
A class that wraps the state of a world - a set of dimensions and the environment of Minecraft.