Bewerken

World Class

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

Properties

afterEvents

read-only afterEvents: WorldAfterEvents;

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.

Type: WorldAfterEvents

Notes:

  • This property can be read in early-execution mode.

allowCheats

allowCheats: boolean;

Enables or disables cheats.

Type: boolean

Caution

This property is still in pre-release. Its signature may change or it may be removed in future releases.

Notes:

  • This property can't be edited in restricted-execution mode.

beforeEvents

read-only beforeEvents: WorldBeforeEvents;

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.

Type: WorldBeforeEvents

Notes:

  • This property can be read in early-execution mode.

Examples

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;
        }
      }
    }
  });
}

(preview) Work with this sample on the MCTools.dev code sandbox.

gameRules

read-only gameRules: GameRules;

The game rules that apply to the world.

Type: GameRules

isHardcore

read-only isHardcore: boolean;

Type: boolean

primitiveShapesManager

read-only primitiveShapesManager: PrimitiveShapesManager;

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

Type: PrimitiveShapesManager

Caution

This property is still in pre-release. Its signature may change or it may be removed in future releases.

scoreboard

read-only scoreboard: Scoreboard;

Returns the general global scoreboard that applies to the world.

Type: Scoreboard

seed

read-only seed: string;

The world seed.

Type: string

structureManager

read-only structureManager: StructureManager;

Returns the manager for @minecraft/server.Structure related APIs.

Type: StructureManager

tickingAreaManager

read-only tickingAreaManager: TickingAreaManager;

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

Type: TickingAreaManager

Methods

broadcastClientMessage

broadcastClientMessage(id: string, value: string): void

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

Parameters

  • id: string

    The message identifier.

  • value: string

    The message.

Caution

This function is still in pre-release. Its signature may change or it may be removed in future releases.

Notes:

  • This function can't be called in restricted-execution mode.

clearDynamicProperties

clearDynamicProperties(): void

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

getAbsoluteTime

getAbsoluteTime(): number

Returns the absolute time since the start of the world.

Returns number

getAimAssist

getAimAssist(): AimAssistRegistry

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

Returns AimAssistRegistry

getAllPlayers

getAllPlayers(): Player[]

Returns an array of all active players within the world.

Returns Player[]

Notes:

getDay

getDay(): number

Returns the current day.

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

getDefaultSpawnLocation

getDefaultSpawnLocation(): Vector3

Returns the default Overworld spawn location.

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.

getDifficulty

getDifficulty(): Difficulty

Gets the difficulty from the world.

Returns Difficulty - Returns the world difficulty.

getDimension

getDimension(dimensionId: string): Dimension

Returns a dimension object.

Parameters

  • dimensionId: string

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

Returns Dimension - The requested dimension

Notes:

  • This function can throw errors.
    • Throws if the given dimension name is invalid

getDynamicProperty

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

Returns a property value.

Parameters

  • identifier: string

    The property identifier.

Returns boolean | number | string | Vector3 | undefined - Returns the value for the property, or undefined if the property has not been set.

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);
}

(preview) Work with this sample on the MCTools.dev code sandbox.

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);
}

(preview) Work with this sample on the MCTools.dev code sandbox.

getDynamicPropertyIds

getDynamicPropertyIds(): string[]

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

Returns string[] - A string array of active dynamic property identifiers.

getDynamicPropertyTotalByteCount

getDynamicPropertyTotalByteCount(): number

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.

Returns number

getEntity

getEntity(id: string): Entity | undefined

Returns an entity based on the provided id.

Parameters

  • id: string

    The id of the entity.

Returns Entity | undefined - The requested entity object.

Notes:

  • This function can throw errors.
    • Throws if the given entity id is invalid.

getLootTableManager

getLootTableManager(): LootTableManager

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

Returns LootTableManager - A loot table manager with a variety of loot generation methods.

getMoonPhase

getMoonPhase(): MoonPhase

Returns the MoonPhase for the current time.

Returns MoonPhase

getPackSettings

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

Returns a map of pack setting name and value pairs.

Returns Record<string, boolean | number | string>

Caution

This function is still in pre-release. Its signature may change or it may be removed in future releases.

Notes:

  • This function can be called in early-execution mode.

getPlayers

getPlayers(options?: EntityQueryOptions): Player[]

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

Parameters

  • options?: EntityQueryOptions = null

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

Returns Player[] - A player array.

Notes:

getTimeOfDay

getTimeOfDay(): number

Returns the time of day.

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

playMusic

playMusic(trackId: string, musicOptions?: MusicOptions): void

Plays a particular music track for all players.

Parameters

Notes:

Examples

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);
}

(preview) Work with this sample on the MCTools.dev code sandbox.

queueMusic

queueMusic(trackId: string, musicOptions?: MusicOptions): void

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

Parameters

  • trackId: string

    Identifier of the music track to play.

  • musicOptions?: MusicOptions = null

    Additional options for the music track.

Notes:

sendMessage

sendMessage(message: (RawMessage | string)[] | RawMessage | string): void

Sends a message to all players.

Parameters

Notes:

  • This function can throw errors.
    • This method can throw if the provided @minecraft/server.RawMessage is in an invalid format. For example, if an empty name string is provided to score.

setAbsoluteTime

setAbsoluteTime(absoluteTime: number): void

Sets the world time.

Parameters

  • absoluteTime: number

    The world time, in ticks.

Notes:

  • This function can't be called in restricted-execution mode.

setDefaultSpawnLocation

setDefaultSpawnLocation(spawnLocation: Vector3): void

Sets a default spawn location for all players.

Parameters

  • spawnLocation: Vector3

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

Notes:

setDifficulty

setDifficulty(difficulty: Difficulty): void

Sets the worlds difficulty.

Parameters

  • difficulty: Difficulty

    The difficulty we want to set the world to.

Notes:

  • This function can't be called in restricted-execution mode.

setDynamicProperties

setDynamicProperties(values: Record<string, boolean | number | string | Vector3 | undefined>): void

Sets multiple dynamic properties with specific values.

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.

Notes:

setDynamicProperty

setDynamicProperty(identifier: string, value?: boolean | number | string | Vector3): void

Sets a specified property to a value.

Parameters

  • identifier: string

    The property identifier.

  • value?: boolean | number | string | Vector3 = null

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

Notes:

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);
}

(preview) Work with this sample on the MCTools.dev code sandbox.

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);
}

(preview) Work with this sample on the MCTools.dev code sandbox.

setTimeOfDay

setTimeOfDay(timeOfDay: number | TimeOfDay): void

Sets the time of day.

Parameters

  • timeOfDay: number | TimeOfDay

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

Notes:

  • This function can't be called in restricted-execution mode.
  • This function can throw errors.
    • Throws if the provided time of day is not within the valid range.

stopMusic

stopMusic(): void

Stops any music tracks from playing.

Notes:

  • This function can't be called in restricted-execution mode.