For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /server/classes/World.md.

Class: World

world

Beta

A class that wraps the state of a world - a set of dimensions and the environment of Minecraft.

Properties

afterEvents

readonly afterEvents: WorldAfterEvents

Early Execution Beta

Remarks

Contains 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.

Privilege

early-execution-readable -


allowCheats

实验性

allowCheats: boolean

Beta World Mutation

Remarks

Enables or disables cheats.

Privilege

Tip

restricted-execution-read-only -


beforeEvents

readonly beforeEvents: WorldBeforeEvents

Early Execution Beta

Remarks

Tip

Contains 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.

Privilege

early-execution-readable -

Example

customCommand.ts

import { world, DimensionLocation } from '@minecraft/server';

function customCommand(targetLocation: DimensionLocation) {
  const chatCallback = world.beforeEvents.chatSend.subscribe(eventData => {
    if (eventData.message.includes('cancel')) {
      // Cancel event if the message contains "cancel"
      eventData.cancel = true;
    } else {
      const args = eventData.message.split(' ');

      if (args.length > 0) {
        switch (args[0].toLowerCase()) {
          case 'echo':
            // Send a modified version of chat message
            world.sendMessage(`Echo '${eventData.message.substring(4).trim()}'`);
            break;
          case 'help':
            world.sendMessage(`Available commands: echo <message>`);
            break;
        }
      }
    }
  });
}

gameRules

readonly gameRules: GameRules

Beta

Remarks

The game rules that apply to the world.


isHardcore

readonly isHardcore: boolean

Beta


primitiveShapesManager

readonly primitiveShapesManager: PrimitiveShapesManager

Beta

Remarks

Manager for adding and removing primitive text objects in the world.


scoreboard

readonly scoreboard: Scoreboard

Beta

Remarks

Returns the general global scoreboard that applies to the world.


seed

readonly seed: string

Beta

Remarks

The world seed.


soundDefinitionRegistry

实验性

readonly soundDefinitionRegistry: SoundDefinitionRegistry

Beta

Preview

Remarks

Provides read-only access to the sound definitions loaded for this world.


structureManager

readonly structureManager: StructureManager

Beta

Remarks

Returns the manager for Structure related APIs.


tickingAreaManager

readonly tickingAreaManager: TickingAreaManager

Beta

Remarks

Manager for adding, removing and querying pack specific ticking areas.

Methods

broadcastClientMessage()

broadcastClientMessage(id, value): void

Beta World Mutation

Parameters

id

string

The message identifier.

value

string

The message.

Returns

void

Remarks

A method that is internal-only, used for broadcasting specific messages between client and server.

Privilege

Tip

no-restricted-execution -


clearDynamicProperties()

clearDynamicProperties(): void

Beta

Returns

void

Remarks

Clears the set of dynamic properties declared for this behavior pack within the world.


getAbsoluteTime()

getAbsoluteTime(): number

Beta

Returns

number

Remarks

Returns the absolute time since the start of the world.


getAimAssist()

getAimAssist(): AimAssistRegistry

Beta

Returns

AimAssistRegistry

Remarks

The aim-assist presets and categories that can be used in the world.


getAllPlayers()

getAllPlayers(): Player[]

Beta

Returns

Player[]

Remarks

Returns an array of all active players within the world.

Throws

This function can throw errors.

CommandError

InvalidArgumentError


getClock()

getClock(name): WorldClock

Beta

Parameters

name

string

The name of the world clock to retrieve.

Returns

WorldClock

The WorldClock with the given name.

Remarks

Retrieves a world clock by its name.

Throws

WorldClockNotFoundError: If the world clock with the given name does not exist.

WorldClockNotFoundError


getDay()

getDay(): number

Beta

Returns

number

The current day, determined by the world time divided by the number of ticks per day. New worlds start at day 0.

Remarks

Returns the current day.


getDefaultSpawnLocation()

getDefaultSpawnLocation(): Vector3

Beta

Returns

Vector3

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.

Remarks

Returns the default Overworld spawn location.


getDifficulty()

getDifficulty(): Difficulty

Beta

Returns

Difficulty

Returns the world difficulty.

Remarks

Gets the difficulty from the world.


getDimension()

getDimension(dimensionId): Dimension

Beta

Parameters

dimensionId

string

The name of the dimension. For example, "overworld", "nether" or "the_end".

Returns

Dimension

The requested dimension

Remarks

Returns a dimension object.

Throws

Throws if the given dimension name is invalid


getDynamicProperty()

getDynamicProperty(identifier): string | number | boolean | Vector3 | undefined

Beta

Parameters

identifier

string

The property identifier.

Returns

string | number | boolean | Vector3 | undefined

Returns the value for the property, or undefined if the property has not been set.

Remarks

Returns a property value.

Throws

Throws if the given dynamic property identifier is not defined.

Examples

incrementDynamicProperty.ts

import { world, DimensionLocation } from '@minecraft/server';

function incrementDynamicProperty(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
  let number = world.getDynamicProperty('samplelibrary:number');

  log('Current value is: ' + number);

  if (number === undefined) {
    number = 0;
  }

  if (typeof number !== 'number') {
    log('Number is of an unexpected type.');
    return -1;
  }

  world.setDynamicProperty('samplelibrary:number', number + 1);
}

incrementDynamicPropertyInJsonBlob.ts

import { world, DimensionLocation } from '@minecraft/server';

function incrementDynamicPropertyInJsonBlob(
  log: (message: string, status?: number) => void,
  targetLocation: DimensionLocation
) {
  let paintStr = world.getDynamicProperty('samplelibrary:longerjson');
  let paint: { color: string; intensity: number } | undefined = undefined;

  log('Current value is: ' + paintStr);

  if (paintStr === undefined) {
    paint = {
      color: 'purple',
      intensity: 0,
    };
  } else {
    if (typeof paintStr !== 'string') {
      log('Paint is of an unexpected type.');
      return -1;
    }

    try {
      paint = JSON.parse(paintStr);
    } catch (e) {
      log('Error parsing serialized struct.');
      return -1;
    }
  }

  if (!paint) {
    log('Error parsing serialized struct.');
    return -1;
  }

  paint.intensity++;
  paintStr = JSON.stringify(paint); // be very careful to ensure your serialized JSON str cannot exceed limits
  world.setDynamicProperty('samplelibrary:longerjson', paintStr);
}

getDynamicPropertyIds()

getDynamicPropertyIds(): string[]

Beta

Returns

string[]

A string array of active dynamic property identifiers.

Remarks

Gets a set of dynamic property identifiers that have been set in this world.


getDynamicPropertyTotalByteCount()

getDynamicPropertyTotalByteCount(): number

Beta

Returns

number

Remarks

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.


getEntity()

getEntity(id): Entity | undefined

Beta

Parameters

id

string

The id of the entity.

Returns

Entity | undefined

The requested entity object.

Remarks

Returns an entity based on the provided id.

Throws

Throws if the given entity id is invalid.


getLootTableManager()

getLootTableManager(): LootTableManager

Beta

Returns

LootTableManager

A loot table manager with a variety of loot generation methods.

Remarks

Returns a manager capable of generating loot from an assortment of sources.


getMoonPhase()

getMoonPhase(): MoonPhase

Beta

Returns

MoonPhase

Remarks

Returns the MoonPhase for the current time.


getPackSettings()

getPackSettings(): Record<string, string[] | boolean | number | string>

Early Execution Beta

Returns

Record<string, string[] | boolean | number | string>

Remarks

Returns a map of pack setting name and value pairs.

Privilege

early-execution-allowed -


getPlayers()

getPlayers(options?): Player[]

Beta

Parameters

options?

EntityQueryOptions

Additional options that can be used to filter the set of players returned.

Returns

Player[]

A player array.

Remarks

Returns a set of players based on a set of conditions defined via the EntityQueryOptions set of filter criteria.

Throws

Throws if the provided EntityQueryOptions are invalid.

CommandError

InvalidArgumentError


getTimeOfDay()

getTimeOfDay(): number

Beta

Returns

number

The time of day, in ticks, between 0 and 24000.

Remarks

Returns the time of day.


playMusic()

playMusic(trackId, musicOptions?): void

World Mutation Beta

Parameters

trackId

string

musicOptions?

MusicOptions

Returns

void

Remarks

Plays a particular music track for all players.

Privilege

Tip

no-restricted-execution -

Throws

This function can throw errors.

PropertyOutOfBoundsError

Example

playMusicAndSound.ts

import { world, MusicOptions, WorldSoundOptions, PlayerSoundOptions, DimensionLocation } from '@minecraft/server';

function playMusicAndSound(targetLocation: DimensionLocation) {
  const players = world.getPlayers();

  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,
  };
  world.playSound('ambient.weather.thunder', targetLocation, worldSoundOptions);

  const playerSoundOptions: PlayerSoundOptions = {
    pitch: 1.0,
    volume: 1.0,
  };

  players[0].playSound('bucket.fill_water', playerSoundOptions);
}

queueMusic()

queueMusic(trackId, musicOptions?): void

World Mutation Beta

Parameters

trackId

string

Identifier of the music track to play.

musicOptions?

MusicOptions

Additional options for the music track.

Returns

void

Remarks

Queues an additional music track for players. If a track is not playing, a music track will play.

Privilege

Tip

no-restricted-execution -

Throws

An error will be thrown if volume is less than 0.0. An error will be thrown if fade is less than 0.0.

PropertyOutOfBoundsError


sendMessage()

sendMessage(message): void

Beta

Parameters

message

string | RawMessage | (string | RawMessage)[]

The message to be displayed.

Returns

void

Remarks

Sends a message to all players.

Throws

This method can throw if the provided RawMessage is in an invalid format. For example, if an empty name string is provided to score.


setAbsoluteTime()

setAbsoluteTime(absoluteTime): void

World Mutation Beta

Parameters

absoluteTime

number

The world time, in ticks.

Returns

void

Remarks

Sets the world time.

Privilege

Tip

no-restricted-execution -


setDefaultSpawnLocation()

setDefaultSpawnLocation(spawnLocation): void

World Mutation Beta

Parameters

spawnLocation

Vector3

Location of the spawn point. Note that this is assumed to be within the overworld dimension.

Returns

void

Remarks

Sets a default spawn location for all players.

Privilege

Tip

no-restricted-execution -

Throws

Throws if the provided spawn location is out of bounds.

Error

LocationOutOfWorldBoundariesError


setDifficulty()

setDifficulty(difficulty): void

World Mutation Beta

Parameters

difficulty

Difficulty

The difficulty we want to set the world to.

Returns

void

Remarks

Sets the worlds difficulty.

Privilege

Tip

no-restricted-execution -


setDynamicProperties()

setDynamicProperties(values): void

Beta

Parameters

values

Record<string, boolean | number | string | Vector3 | undefined>

A Record of key value pairs of the dynamic properties to set. If the data value is null, it will remove that property instead.

Returns

void

Remarks

Sets multiple dynamic properties with specific values.

Throws

This function can throw errors.

ArgumentOutOfBoundsError


setDynamicProperty()

setDynamicProperty(identifier, value?): void

Beta

Parameters

identifier

string

The property identifier.

value?

string | number | boolean | Vector3

Data value of the property to set. If the value is null, it will remove the property instead.

Returns

void

Remarks

Sets a specified property to a value.

Throws

Throws if the given dynamic property identifier is not defined.

ArgumentOutOfBoundsError

Examples

incrementDynamicProperty.ts

import { world, DimensionLocation } from '@minecraft/server';

function incrementDynamicProperty(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
  let number = world.getDynamicProperty('samplelibrary:number');

  log('Current value is: ' + number);

  if (number === undefined) {
    number = 0;
  }

  if (typeof number !== 'number') {
    log('Number is of an unexpected type.');
    return -1;
  }

  world.setDynamicProperty('samplelibrary:number', number + 1);
}

incrementDynamicPropertyInJsonBlob.ts

import { world, DimensionLocation } from '@minecraft/server';

function incrementDynamicPropertyInJsonBlob(
  log: (message: string, status?: number) => void,
  targetLocation: DimensionLocation
) {
  let paintStr = world.getDynamicProperty('samplelibrary:longerjson');
  let paint: { color: string; intensity: number } | undefined = undefined;

  log('Current value is: ' + paintStr);

  if (paintStr === undefined) {
    paint = {
      color: 'purple',
      intensity: 0,
    };
  } else {
    if (typeof paintStr !== 'string') {
      log('Paint is of an unexpected type.');
      return -1;
    }

    try {
      paint = JSON.parse(paintStr);
    } catch (e) {
      log('Error parsing serialized struct.');
      return -1;
    }
  }

  if (!paint) {
    log('Error parsing serialized struct.');
    return -1;
  }

  paint.intensity++;
  paintStr = JSON.stringify(paint); // be very careful to ensure your serialized JSON str cannot exceed limits
  world.setDynamicProperty('samplelibrary:longerjson', paintStr);
}

setTimeOfDay()

setTimeOfDay(timeOfDay): void

World Mutation Beta

Parameters

timeOfDay

number

The time of day, in ticks, between 0 and 24000.

Returns

void

Remarks

Sets the time of day.

Privilege

Tip

no-restricted-execution -

Throws

Throws if the provided time of day is not within the valid range.


stopMusic()

stopMusic(): void

World Mutation Beta

Returns

void

Remarks

Stops any music tracks from playing.

Privilege

Tip

no-restricted-execution -

同领域相关