#Script API General

1 messages Β· Page 33 of 1

warm mason
#

code

steady canopy
warm mason
#

is there a error in the game?

wary edge
#

Again, did you update your types?

steady canopy
#

i did

steady canopy
warm mason
#

then you have problems with the code editor. This is not for me

gentle mist
#

Hey does someone have a force show function?

remote oyster
# steady canopy

server-ui may be overriding your server module with the stable version and not actually enforcing the beta version you are requesting. This is because the server-ui has a dependency for the stable version and it causes conflicts. I personally work around this issue doing the following:

"dependencies": {
    "@minecraft/server-ui": "1.4.0-beta.1.21.44-stable",
    "@minecraft/server": "1.16.0-beta.1.21.44-stable"
},
"overrides": {
    "@minecraft/server-ui": {
        "@minecraft/server": "1.16.0-beta.1.21.44-stable"
    }
}

Try this and execute npm i to see if that resolved it. You may or may not need to wipe out the node_modules folder too and repopulate it with the npm i command.

gentle mist
#

Anyone know how i can add to my chest ui that if i click a item i will get tped to like my arena with the kit equipped?

gentle mist
#

Can someome help pls

sharp elbow
#

Do you have the Content Log enabled? In Settings β†’ Creator (command block icon)

#

Pack imports usually don't throw errors to the log but it can. There may be more information there

gentle mist
#

U mean in minecraft?

#

@sharp elbow

sharp elbow
#

Having the file on with GUI off isn't too helpful. Toggle those both

#

Once that's done, try importing your mcpack again

gentle mist
#

Thats sus

#

Do u wanna see my pack?

#

Maybe something there is wrong

#

Thats what i wanna test but i cant import it

spring axle
dim tusk
#

Guys... Is destructing the cancel in the before events work now or still nah?

world.beforeEvents.chatSend.subscribe(({ message, sender, cancel }) => {
   if (message === '!test') {
      cancel = true;
      sender.sendMessage('bruh');
   }
});```
dim tusk
granite badger
#

it won't work if you dereference cancel

distant tulip
#

reminder for me to fix my bot

solar dagger
distant tulip
#

for what

thorn flicker
solar dagger
# distant tulip for what

I'm using an item to make changes to an entity but the player won't necessarily be interacting with it.

solar dagger
thorn flicker
# solar dagger How?

entity.setDynamicProperty('whatever', entity.id)
player.setDynamicProperty('whatever', entity.id)
world.setDynamicProperty('whatever', entity.id)

solar dagger
#

These save even if the player leave right?

thorn flicker
#

yes

solar dagger
#

πŸ‘Œ

junior hill
#

I wish getRotation() was a thing for players

thorn flicker
junior hill
thorn flicker
#

setRotation I believe, does not

junior hill
#

O i was thinkin of setRotation

dim tusk
#

I just asked, cause I saw in someone's code that did destructure it directly instead of using a short name

neat hazel
#

Why doesn't it work?

shy leaf
#

you need to get dimension from players

#

(also playAnimation native function exists)

thorn flicker
#

so do player.runCommandAsync

#

however I recommend using the native method to play animations

shy leaf
#

or that

#

i forgot player also has command function

thorn flicker
neat hazel
shy leaf
#

what

neat hazel
shy leaf
#

oh

shy leaf
dim tusk
shy leaf
#

you can just get all entities and do playAnimation on the entities

dim tusk
#

Simple as that

thorn flicker
#

no, it'll try to run the animation on the player

#

you need to get the entities in the world

dim tusk
thorn flicker
#

refer to this help post I was in

dim tusk
#
const entity = world.getDimension('overworld').getEntities({ tags: [] });
entity?.playAnimation()```
dim tusk
thorn flicker
#

you need to loop it, its an array

dim tusk
dim tusk
#

-# that's why I use find()

thorn flicker
dim tusk
#

or just add [0]

shy leaf
thorn flicker
#

that indexes it to the first entity in the array

dim tusk
#

haha

dim tusk
thorn flicker
#

find would probably do the same thing

#

except, you can add conditions

dim tusk
#

Idk I just use it simple things lol

neat hazel
thorn flicker
#

its not about it being simple, its about what it does

dim tusk
#
const entity = world.getDimension('overworld').getEntities().find(entity => entity.typeId === '');
entity?.playAnimation()```
shy leaf
#

:skull

thorn flicker
#

oml

dim tusk
thorn flicker
dim tusk
#

@neat hazel

#

Forget what I did

#

I messed so bad

dim tusk
thorn flicker
shy leaf
#

me when js for

i cant believe i had to edit that

thorn flicker
#

if thats what you want, cool

subtle cove
#
const query = {type"n:madara", tags:["died"]} 
for (const e of getEntities(query)) {
    //e.playAnimation()
    //e.matches(query) && e.playAnimation()
}```
subtle cove
#

Its just outline

thorn flicker
#

if I was hash rn I would close discord

neat hazel
subtle cove
#

But yeh, the dimensions has to be specified

thorn flicker
#

okay

#

hang tight, brb.

dim tusk
#

But yeah...

#

I messed up so badly guys

#

Sorry I fumbled not once but 4 time

thorn flicker
#

also if you can, I recommend using animation controllers instead, more performant.

near siren
#

Has anymore encountered items in bundles sometimes disappearing when you move them between containers?

slow walrus
#

Here's a nicer version:

export namespace UUID {
  const LUT: string[] = Array.from<string, string>({ length: 256 }, (_v, i) => {
    return i.toString(16).padStart(2, '0')
  })

  /**
   * Generates a random UUID (RFC4122 version 4 compliant).
   * @returns {string} The generated UUID.
   */
  export function generate(): string {
    const r = (Math.random() * 0x100000000) >>> 0
    const s = (Math.random() * 0x100000000) >>> 0
    const t = (Math.random() * 0x100000000) >>> 0
    const u = (Math.random() * 0x100000000) >>> 0

    return [
      LUT[r & 0xff],
      LUT[(r >> 8) & 0xff],
      LUT[(r >> 16) & 0xff],
      LUT[(r >> 24) & 0xff],
      '-',
      LUT[s & 0xff],
      LUT[(s >> 8) & 0xff],
      '-',
      LUT[((s >> 16) & 0x0f) | 0x40],
      LUT[(s >> 24) & 0xff],
      '-',
      LUT[(t & 0x3f) | 0x80],
      LUT[(t >> 8) & 0xff],
      '-',
      LUT[(t >> 16) & 0xff],
      LUT[(t >> 24) & 0xff],
      LUT[u & 0xff],
      LUT[(u >> 8) & 0xff],
      LUT[(u >> 16) & 0xff],
      LUT[(u >> 24) & 0xff]
    ].join('')
  }

  /**
   * Validates a given UUID string.
   * @param {string} uuid - The string to validate as a UUID.
   * @returns {boolean} - Returns true if the string is a valid UUID, false otherwise.
   */
  export function isValid(uuid: string): boolean {
    const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
    return regex.test(uuid)
  }
}
#

performance is a lil better cause you don't have to build the LUT every time

slow walrus
#

lol why

#

cause I edited it?

dim tusk
# slow walrus Here's a nicer version: ```ts export namespace UUID { const LUT: string[] = Ar...

Here's a much nicer version for Android users:
-# this is a joke

export namespace UUID {
  const LUT: string[] = Array.from<string, string>({ length: 256 }, (_v, i) => {
    return i.toString(16).padStart(2, '0')
  })

  /**
   * Generates a random UUID (RFC4122 version 4 compliant).
   * @returns {string} The generated UUID.
   */
  export function generate(): string {
    const r = (Math.random() * 0x100000000) >>> 0
    const s = (Math.random() * 0x100000000) >>> 0
    const t = (Math.random() * 0x100000000) >>> 0
    const u = (Math.random() * 0x100000000) >>> 0

    return [
      LUT[r & 0xff],
      LUT[(r >> 8) & 0xff],
      LUT[(r >> 16) & 0xff],
      LUT[(r >> 24) & 0xff],
      '-',
      LUT[s & 0xff],
      LUT[(s >> 8) & 0xff],
      '-',
      LUT[((s >> 16) & 0x0f) | 0x40],
      LUT[(s >> 24) & 0xff],
      '-',
      LUT[(t & 0x3f) | 0x80],
      LUT[(t >> 8) & 0xff],
      '-',
      LUT[(t >> 16) & 0xff],
      LUT[(t >> 24) & 0xff],
      LUT[u & 0xff],
      LUT[(u >> 8) & 0xff],
      LUT[(u >> 16) & 0xff],
      LUT[(u >> 24) & 0xff]
    ].join('')
  }

  /**
   * Validates whether a given string is a valid UUID.
   * @param {string} uuid - The string to validate as a UUID.
   * @returns {boolean} - Returns true if the string is a valid UUID, false otherwise.
   */
  export function isValid(uuid: string): boolean {
    const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
    return regex.test(uuid)
  }
}
dim tusk
slow walrus
#

oh does typescript not get formatted on android?

#

that's goofy

dim tusk
#

Only in desktop

remote oyster
slow walrus
#

eh nevermind not really

#

they're similar readability lmao

#

jsut whatever you wanna use ig

gentle mist
untold magnet
#

guys, how can i increase the inventory size of my entity using scripts?
Bridge is broken again, i cant use getComponentpepesad

#

const inv = entity.getComponent('inventory').container;
inv.size ???

random flint
untold magnet
distant tulip
#

not possible

untold magnet
#

im so geniust17xBoost

#

i found a way to fix multiple issues happening to me

slow walrus
untold magnet
dim tusk
#

Guys, is before events of playerInteractWithEntity beta or nah now

untold magnet
#

probably

#

has to be

dim tusk
dim tusk
untold magnet
#

yah it is stable now,

dim tusk
#

😧

untold magnet
#

lemme make sure

dim tusk
#

Because I'm sure the player break block and place is already stable now

untold magnet
#

@dim tusk

#

stable

#

interacting with blocks or entities before and after events are stable now

dim tusk
#

Nice thanks, I'm pretty lazy to open the changelog

chilly fractal
#

Yo is there a way to set the xp of the player?

#

Reset*

#

Like a method, instead of getting xp and adding -xp gotten

#

To reset.

#

To 0...

#

There is resetLevel but it doesn't reset xp

#

Yeah there probably isn't a way.

#

I'll just reset using some calculations

warm mason
winter plaza
#
import * as mc from "@minecraft/server";

mc.system.afterEvents.scriptEventReceive.subscribe(event => {
    const wg = event.id.split("wg:")[1];
    const player = event.sourceEntity;
    switch (wg) {
      case "plains":
        biome(player, "plains");
      break
  }
});

function biome(player, biome) {
  let biomeLocation = player.dimension.findClosestBiome(player.location, biome);
  player.runCommand(`tellraw @s {"rawtext":[{"text":"Coords: ${biomeLocation}"}]}`);
}
#

help me

#

what's wrong?

slow walrus
#

otherwise change the [1] to [0]

warm mason
#

Brilliant

#
import * as mc from "@minecraft/server";

mc.system.afterEvents.scriptEventReceive.subscribe(event => {
    const wg = event.id.split(":")[1];
    const player = event.sourceEntity;
    biome(player, wg)
});

function biome(player, biome) {
  let biomeLocation = player.dimension.findClosestBiome(player.location, biome);
  player.runCommand(`tellraw @s {"rawtext":[{"text":"Coords: ${biomeLocation}"}]}`);
}```
slow walrus
warm mason
#

just do a try catch, if the error means the biome is not valid

random flint
random flint
slow walrus
warm mason
#

Or check for the presence of a biome in biome types

warm mason
#

no

slow walrus
#

without the message it'll just not send at all

warm mason
slow walrus
#

afaik

winter plaza
#

and now? 😦

#

the best scripts are always beta

warm mason
#

It’s just that when they come out of beta you already get used to them and consider them not the best

winter plaza
#

lol

warm mason
#

I think the best ones are playerInteractWithBlock and itemUse events and system.runTimeout

winter plaza
#

Is there another way for me to find out the location of a biome?

warm mason
#

no

winter plaza
#

/locate only works if you type it in chat, it doesn't work as a command in addons

distant tulip
#

it dose work
just no way of knowing the location it output

#

i guess it can be used to check if a structure/biome is present in a world

winter plaza
#

I put, "/locate biome plains" in a function, and when I activate it nothing happens

dim tusk
#

Found this.

// Script by WavePlayz

import { world, system, BlockTypes } from "@minecraft/server"; // Import necessary modules from the Minecraft server API

// Listen for the `chatSend` event, which is triggered when a player sends a message in chat
world.afterEvents.chatSend.subscribe(async (eventData) => {
    // Destructure the `eventData` object to get the sender (player who sent the message) and the message itself
    const { sender, message } = eventData;

    // Check if the player sent the message "find biome"
    if (message === "find biome") {
        // Send a message to all players in the world, asking the player to close the chat
        world.sendMessage("Close chat (2s)");

        // Wait for 2 seconds (40 ticks) before continuing the script
        await system.waitTicks(20 * 2);

        // Define the biome ID to search for (in this case, "plains")
        const biomeId = BlockTypes.get("plains").id;

        // Define the dimensions of the bounding box (the area within which the search will be conducted)
        const length = 100;
        const height = 100;
        const width = 100;

        // Create a `BiomeSearchOptions` object with the defined bounding box dimensions
        const biomeSearchOptions = {
            boundingSize: { x: length, y: height, z: width },
        };

        // Use the player's current dimension to find the closest biome matching the specified `biomeId`
        // The search will start from the player's current location and use the `biomeSearchOptions`
        const biomeLocation = sender.dimension.findClosestBiome(
            sender.location,
            biomeId,
            biomeSearchOptions
        );

        // Check if a biome was found
        if (biomeLocation) {
            // If found, send a message to the player with the coordinates of the biome
            sender.sendMessage(
                `Found biome '${biomeId}' at location: ${biomeLocation.x}, ${biomeLocation.y}, ${biomeLocation.z}`
            );
        } else {
            // If not found, send a message to the player indicating that the biome was not found
            sender.sendMessage(`Biome '${biomeId}' not found`);
        }
    }
});```
warm mason
dim tusk
untold magnet
#

const invo = entity.getComponent('inventory').container;bao_icon_entities

dim tusk
#

Don't tell it's player

slow walrus
#

ignore me I'm braindead

untold magnet
# slow walrus ignore me I'm braindead

can u help me detecting 3 extra slots in the player inventory?
i used this "minecraft:inventory": {"container_type": "container","can_be_siphoned_from": true,"inventory_size": 3} inside of the player.json and it did give the player 3 extra invisible slots, i wanna make sure i can detect those slots.

slow walrus
#

no

#

dont crosspost

#

and dont ping for a random question lol

cold grove
#

Tch tch tch

untold magnet
chilly fractal
untold magnet
#

via script?

cold grove
#

Idk, what channel is this?

untold magnet
#

i tried the normal way ( player.getComponent('inventory') ) and i cant detect the new extra slots

#

I'm trying to detect those extra slots via scripts, i wanna make sure its 100% impossiblepepe_listening

cold grove
#

Then minecraft doenst support new slots

untold magnet
#

just like normal entities, u can open it by interacting with the entity,

wary edge
#

Is there a onxpreceieve event or something?

gentle mist
#

Do u mean mw?

#

Me*

junior hill
#

Is input api in beta?

gentle mist
#

Are u guys talking with me

#

Why its not working, can some give me a good explain and help me with that please

gentle mist
#

Please i need that

neat hazel
#

Is it possible to spawn an item on the ground?

neat hazel
#

How? spawnItem? Or something like that

wary edge
#

Yep, Dimension.spawnItem.

gentle mist
strong oar
#

Is it possible to make a script to change the models and texture of the leaves before entering the Minecraft world?

abstract cave
#

is there a way to do item use without an item in the hand

distant tulip
neat hazel
gentle mist
dim tusk
gentle mist
#

ˋˋhìˋˋ

valid ice
#

Triple backticks

#

``` text ```
text

gentle mist
#

EquipmentSlot { Chest } 'minecraft:diamond_chestplate'
what would that do

knotty plaza
#

What is that πŸ’€

valid ice
#

that... wouldn't do anything

gentle mist
#

Idk πŸ’€

knotty plaza
#

I guess you want to equip a chestplate to the player

gentle mist
#

Im new and im trying to equip body with armor stuff with a code

knotty plaza
#
const equippable = player.getComponent('equippable');
equippable.setEquipment('Chest', new ItemStack('diamond_chestplate'));
gentle mist
#

And if i want Helmet just

const equippable = player.getComponent('equippable');
equippable.setEquipment('Head', new ItemStack('diamond_chestplate'));
knotty plaza
#

I think its obvious but you have to get the player in some way first

gentle mist
#

Nah u are the best man

knotty plaza
#

Remember changing what piece of armor you are setting

gentle mist
#

Yes

const equippable = player.getComponent('equippable');
equippable.setEquipment('Head', new ItemStack('diamond_helmet'));
dim tusk
#

Guys, do you think you can recreate block blasts in mc?

dim tusk
slim spear
#

block blasts can mean many things

#

I'm not sure what you mean

slim spear
#

Oh

#

maybe

dim tusk
# slim spear Oh

I'll try doing it. I just need to know the list of shapes lmao

distant gulch
#

chat

#

how do i enable beta api's on my bds

winter plaza
#
import * as mc from "@minecraft/server";

mc.system.afterEvents.scriptEventReceive.subscribe(event => {
    const wg = event.id.split(":")[1];
    const player = event.sourceEntity;
    biome(player, wg)
});

function biome(player, biome) {
  let biomeLocation = player.dimension.findClosestBiome(player.location, biome);
  player.runCommand(`tellraw @s {"rawtext":[{"text":"Coords: ${biomeLocation}"}]}`);
}
#

appears is "object Object" lol

valid ice
#

JSON.stringify() it

winter plaza
#

what?

wary edge
#

You'll need to JSON.stringify(biomeLocation) or do biomeLocation.x

winter plaza
#

Ah ok

#

thanks

#

${JSON.stringify(biomeLocation)}

queen prism
#

system.runInterval(() => {
    ["minecraft:overworld", "minecraft:nether", "minecraft:the_end"].forEach((dimension) => {
        for (let entity of world.getDimension(dimension).getEntities({ type: "addon:jane" })) {
            const ridingComp = entity.getComponent("riding");
            const ridingPig = ridingComp?.entityRidingOn?.typeId === "minecraft:pig";
            const ridingHorse = ridingComp?.entityRidingOn?.typeId === "minecraft:horse";
            entity.setProperty("addon:riding", ridingPig ? 1 : ridingHorse ? 2 : 0);

            entity.setProperty("addon:sheared", entity?.hasComponent("minecraft:is_sheared") ? 1 : 0);

            const equip = entity.getComponent('equippable');
            const main = equip.getEquipmentSlot('Mainhand');
            console.error(main?.typeId ?? 'minecraft:air');
        }
    });
}, 5);```

How do I fix the error that `equip.getEquipmentSlot` causes?
wary edge
queen prism
#

Oh....

queen prism
wary edge
subtle cove
#

use getEquipment

queen prism
# wary edge What are you trying to do?

This.

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

system.runInterval(() => {
    ["minecraft:overworld", "minecraft:nether", "minecraft:the_end"].forEach((dimension) => {
        for (let entity of world.getDimension(dimension).getEntities({ type: "addon:jane" })) {
            const ridingComp = entity.getComponent("riding");
            const ridingPig = ridingComp?.entityRidingOn?.typeId === "minecraft:pig";
            const ridingHorse = ridingComp?.entityRidingOn?.typeId === "minecraft:horse";
            entity.setProperty("addon:riding", ridingPig ? 1 : ridingHorse ? 2 : 0);

            entity.setProperty("addon:sheared", entity?.hasComponent("is_sheared") ? 1 : 0);

            const equip = entity.getComponent("equippable");
            const main = equip?.getEquipmentSlot("Mainhand");

            if (main && ["minecraft:bowl", "minecraft:poisonous_potato", "minecraft:spider_eye"].includes(main.typeId)) {
                entity.dimension.playSound("jane.mob.reject", entity.location, { volume: 0.6, pitch: 0.8 });
                entity.dimension.spawnItem(main, entity.location);
                entity.runCommand("replaceitem entity @s slot.weapon.mainhand 0 air");
                entity.runCommand("say test");
            } else if (main?.typeId === "minecraft:cake") {
                entity.triggerEvent("minecraft:become_witch");
                entity.dimension.playSound("jane.mob.reject", entity.location, { volume: 0.6, pitch: 0.8 });
                entity.runCommand("replaceitem entity @s slot.weapon.mainhand 0 air");
                entity.runCommand("say test2");
            }
        }
    });
}, 5);```

This one. But this didn't work so I reverted back to zero.
subtle cove
#

ContainerSlot needs to have slot.hasItem() for checking

queen prism
#

@dim tusk

olive rapids
#

Does anyone know how I can make a menu with information appear when I enter the world?

#
//import from the menu module if you are going to use the Hit event put it here
import {ActionFormData} from '@minecraft/server-ui'


//event you want to put for example 
//world.afterEvents.itemUse.subscribe

Function miMenu(player){
    const mimenu = New ActionFormData();
      mimenu.title('Β§lΒ§6WELCOME!'
    mimenu.body('text hello how are you all')

 mimenu.show(player)



}//Call the function with a return miMenu(player)

#

How can I do it?

#

I want a menu to appear when I enter the world, a welcome menu

dim tusk
remote oyster
# olive rapids Does anyone know how I can make a menu with information appear when I enter the ...
import { world } from "@minecraft/server";
import { MessageFormData } from "@minecraft/server-ui";

// Subscribe to player spawn event
world.afterEvents.playerSpawn.subscribe((event) => {

    // Function to greet the player
    function greetPlayer(player) {
        const greetGUI = new MessageFormData();
        
        // Set title and body for the greeting message
        greetGUI.title("Β§lΒ§6WELCOME!"); // Title
        greetGUI.body("Hello, how are you? Welcome to the server!"); // Body text

        // Define two buttons
        greetGUI.button1("Thank You!");  // Button 1: Acknowledge
        greetGUI.button2("Exit");        // Button 2: Exit

        // Show the form to the player and handle their selection
        greetGUI.show(player)
            .then((result) => {
                // If the form was canceled due to "UserBusy", recall the function
                if (result && result.canceled && result.cancelationReason === "UserBusy") {
                    greetPlayer(player); // Recall the function to show the message again
                    return; // Exit the current flow
                }

                // Handle button selections
                if (result.selection === 0) {
                    // Acknowledge message
                    player.sendMessage("Thank you for joining! Have fun!");
                } else if (result.selection === 1) {
                    // Kick the player if they select Exit
                    world.getDimension(player.dimension.id).runCommand(`kick ${player.name} Β§oΒ§7\n\nYou have selected to exit.`);
                }
            })
            .catch((error) => {
                // Log any errors that occur
                console.error("Error showing greeting: ", error);
            });
    }

    // Call the greeting function for the player
    greetPlayer(event.player);

});
dim tusk
queen prism
# dim tusk Yea?

It was an earlier moment when I wanted the scripts with the run commands to work lol, nevermind that.

olive rapids
olive rapids
#

❀️

hidden bramble
#

How do I use the script debugger bot?

dim tusk
#

been awhile since i touch block permutation, when you set it's permutation every tick, does it make you unable to break it or place anything besides i?

dim tusk
#

how do i use simulated players?
-# never used them in my life lmao

somber cedar
#
import * as gameTest from '@minecraft/server-gametest';

gameTest
    .register('StarterTests', 'playerTest', (test: gameTest.Test) => {
        const player = test.spawnSimulatedPlayer({ x: 5, y: 2, z: 5 });
    })
    .maxTicks(400)
    .structureName('gametests:mediumglass');
dim tusk
somber cedar
#

that's how you spawn a simulated player

dim tusk
#

Guys, do you think we can recreate the hole filler of mc java to bedrock?

#

I mean obviously you could...
-# I suck at math people

chilly fractal
#

Search a 5x5 area around the hole & if it's air and the same level as the outer ring or same level as inner ring set the block and what's above it to whatever block.

#

It's gonna require some logic

#

@honest spear uhhh sorry for the ping, really really sorry, but your database has some error when I try to load an item

#

If we can move to dms it'd be appreciated too.

honest spear
#

Are you on preview?

chilly fractal
#

Nope, stable minecraft, 1.21.43

honest spear
#

And last question is if you try to use it in new world ?

chilly fractal
#

A normal item, just I have an inventory saver system, I get the Player's Inventory, if it's not undefined it gets saved in the database.

chilly fractal
#

You mean the database?

#

Or the item?

chilly fractal
#

Also it seems you don't clone the item using .clone() right?

honest spear
#

Looks like the default serializer for enchantments is outdated

chilly fractal
#

Cuz I tested also with a shulker with items and it got reset.

#

Yea

#

Now it's EnchantmentType

#

For the type

honest spear
#

i wouldn't recommend saving items with serializers as they can't save all

chilly fractal
#

Yeah ik

honest spear
#

use entity inventories

chilly fractal
#

Alright then. Been nice talking to ya!

honest spear
#

i wish i could help more but serializers are mean to be for custom data types and API are not the best practice

chilly fractal
winter plaza
#
import * as mc from "@minecraft/server";

mc.system.afterEvents.scriptEventReceive.subscribe(event => {
    const wg = event.id.split(":")[1];
    const player = event.sourceEntity;
    switch (wg) {
      case 'plains':
        biome(player, "plains");
      break
    }
});

function biome(player, biome) {
  let biomeLocation = player.dimension.findClosestBiome(player.location, biome);
  player.runCommand(`tellraw @s {"rawtext":[{"text":"Coords: ${JSON.stringify(biomeLocation)}"}]}`);
}
[Scripting][error]-CommandError: Syntax error: "z": unexpected in "Coords: {"Β»zΒ«":-5,"y":-"
    at biome (biome.js:15)
    at <anonymous> (biome.js:8)
#

help

warm mason
#

By the way, I don’t recommend naming variables and functions the same

#

Better yet, use API methods rather than commands

warm mason
#
function biome(player, biome) {
  let biomeLocation = player.dimension.findClosestBiome(player.location, biome);
  player.sendMessage("Coords: " + JSON.stringify(biomeLocation));
}
winter plaza
#

Thanks!

solar dagger
#

Are we not able to use a translation text from the lang file?

winter plaza
#
import * as mc from '@minecraft/server';

mc.system.runInterval(() => {
  for (const player of mc.world.getPlayers()) {
    for (const entity of mc.world.getDimension("overworld").getEntities({excludeFamilies:["inanimate"],excludeTypes:["item","xp_orb"]})) {
      entity.nameTag = `${entity.typeId.replace('_', '').split(":")[1]}`;
    }
  }
}, 5);
winter plaza
#

mobs that have "_" appear undefined

#

since I put .replace('_')

warm mason
#

.replace('_', '')

winter plaza
#

Ohhh ok

warm mason
sterile epoch
#

does anyone know how I could format a date object? like instead of telling the player : "you have been banned until (date)" it says "you have been banned for "24d, 4h, 2m"

remote oyster
# sterile epoch does anyone know how I could format a date object? like instead of telling the p...

One of many possibilities

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

// Assuming `banEndTime` is a timestamp in milliseconds when the ban ends
function getBanDuration(banEndTime) {
    const currentTime = Date.now();
    const timeDifference = banEndTime - currentTime;

    // Calculate days, hours, and minutes
    const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
    const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));

    // Format the duration
    return `${days}d, ${hours}h, ${minutes}m`;
}

// Example usage
const banEndTime = Date.now() + (24 * 24 * 60 * 60 * 1000) + (4 * 60 * 60 * 1000) + (2 * 60 * 1000); // 24 days, 4 hours, 2 minutes from now
const banDuration = getBanDuration(banEndTime);
world.sendMessage(`You have been banned for ${banDuration}`);
sterile epoch
#

Thank you

prisma shard
#

gop gop

#

!!!!

#

im a rare sight now

fallow minnow
fallow minnow
#

how do i get all of the players within 3 blocks of an entity

warm mason
random flint
#

dimension.getEntities + EntityQueryOption

warm mason
random flint
#

I was blind when looking at the docs

untold magnet
#

ah, whats the difference between itemStackAfterBreak and itemStackBeforeBreak inside of the playerBreakBlock component?

distant tulip
untold magnet
#

I'll use afterBreak one, I'll detect the item and damage the item durability only

distant tulip
#

let say you broke a block with 1 durability pickaxe
the pickaxe will break and itemStackAfterBreak should return undefined

untold magnet
chilly fractal
#

It doesn't matter, depending on usage, if you wanna cancel the event use before, otherwise it's better to use after

#

Just make sure you have a check statement

#

if (!item) return;

#

Now anyway

#

So minecraft decides that js p.nameTag = `Β§cΒ§l${(p.getComponent('health').currentValue/2).toFixed(1)} Β§4Hearts Β§r${gemTypeColorCode[gID]}(${gID.charAt(0).toUpperCase()+gID.substring(1)})\nΒ§r${t !== undefined ? `Β§g[Β§8${t.split(':')[1]}Β§rΒ§g] ` : ''}${nC !== undefined ? nC.split(':')[1] : 'Β§7'}${p.name}Β§r`; has used something that isn't a function. [Scripting][error]-TypeError: not a function at updateNameTag (functions/mcUtils.js:29) at <anonymous> (functions/eventFunctions.js:83)

#

If anyone can tell me who is high, me or the game. Please do.

#

And yes t is team, it's valid, nC is name color, it's valid and p is player & it's also valid.

#

And gID is the gem ID and it's triple quadruple valid.

#

And also don't trust the discord highlighting, I can have inside of ${} inside of fine.

winter plaza
#

nC.split(':")[1] >>> nC.split(':')[1]

#

"`"

chilly fractal
#

And ` works fine.

winter plaza
#

very confusing

chilly fractal
#

Yes.

distant tulip
#

break in into lines to get the exact error location

warm mason
#

I remember that the toUpperCase and toLowerCase methods work strangely

chilly fractal
#

I decided to do the black magic voodoo of making my code unreadable to troll my friends when they try to edit the addon when it's on the server.

chilly fractal
#

That's why I only use it on char(0)

chilly fractal
warm mason
chilly fractal
#

They work fine

winter plaza
#
import * as mc from "@minecraft/server"
import { ItemStack } from "@minecraft/server";

mc.world.beforeEvents.playerBreakBlock.subscribe(data => {
    const player = data.player,
      block = data.block,
      inventoryComponent = player.getComponent(mc.EntityInventoryComponent.componentId),
      item = inventoryComponent.container.getItem(player.selectedSlotIndex),
      test = new ItemStack('mob_spawner', 1);
    if (item.typeId != "minecraft:netherite_pickaxe" || block.permutation.type.id != "minecraft:mob_spawner") return;
    block.dimension.runCommandAsync(`summon pig ${block.location.x} ${block.location.y} ${block.location.z} ~~`);
    block.dimension.spawnItem(test, {x:block.location.x, y:block.location.y, z:block.location.z});
});
#

says there is an error in spawnItem

chilly fractal
#

Why not just do block.location instead of your {}

#

I mean ur not editing the value?

warm mason
#

Why all this?... Why?...........

#

Privilege..

#

.

chilly fractal
#

Also block will return undefined

#

Because it's already broken.

warm mason
chilly fractal
#

It won't even work.

#

It needs player.dimension

warm mason
#

There is no such thing as an undefined block, it comes with an air type

#

And here beforeEvents

distant tulip
#

also test var is not initialized

warm mason
#

And I already found his problem

chilly fractal
warm mason
chilly fractal
#

He just used a voodoo technique I use for initializing multiple variables

gaunt salmonBOT
chilly fractal
warm mason
distant tulip
wary edge
warm mason
winter plaza
#

I don't understand, what's wrong with the code?

distant tulip
warm mason
distant tulip
#

it is one of them

untold magnet
chilly fractal
#

Just do ```js
mc.system.run(() => {
block.dimension.spawnEntity("pig", block.location);
block.dimesion.spawnItem(test, block.location);
});

distant tulip
#

replace the command with
block.dimension.spawnEntity("pig", block.location);

warm mason
winter plaza
chilly fractal
warm mason
distant tulip
#

const var1 = ...,
var2 = ...
i guess i learned something new today

slim spear
#

hm?

wary edge
#

Java can do that as well.

distant tulip
#

never used java

wary edge
#

I think most languages can do that as well.

distant tulip
#

@winter plaza

import * as mc from "@minecraft/server"

mc.world.beforeEvents.playerBreakBlock.subscribe(data => {
    const {player, block} = data,
      inventoryComponent = player.getComponent(mc.EntityInventoryComponent.componentId),
      item = inventoryComponent.container.getItem(player.selectedSlotIndex),
      test = new mc.ItemStack('mob_spawner', 1);
    if (item.typeId != "minecraft:netherite_pickaxe" || block.permutation.type.id != "minecraft:mob_spawner") return;
    mc.system.run(() => {
        block.dimension.spawnEntity("pig", block.location);
        block.dimension.spawnItem(test, block.location);
    });
});
distant tulip
warm mason
distant tulip
#

lol
yeah i thought that was an error

warm mason
wary edge
#

It's a preference.

#

I usually write the vars in one line if they're related to one another. IE count and index.

distant tulip
#

i hate using the enum stuff for some reason
mc.EntityInventoryComponent.componentId

warm mason
wary edge
#

That's cool buddy.

warm mason
winter plaza
#

Thanks!!

thorn flicker
#

@burnt musk
you need buttons for all forms.

chilly fractal
#
p.nameTag = `Β§cΒ§l${
 (p.getComponent('health').currentValue/2).toFixed(1)} Β§4Hearts
 Β§r${gemTypeColorCode[gID]}
(${gID.charAt(0)
.toUpperCase()
+gID.substring(1)})
\nΒ§r${t !== undefined ? `Β§g[Β§8${t.split(':')[1]}Β§rΒ§g] ` : ''}
${nC !== undefined ? nC.split(':')[1] : 'Β§7'}
${p.name}Β§r`;```
Bruh it says that .charAt() isn't a function πŸ’€
warm mason
chilly fractal
#

String

granite badger
#

try using the debugger

chilly fractal
#

Gotten from a database

thorn flicker
chilly fractal
chilly fractal
#

Ima log gID

wary edge
#

Haha, sometimes...doing it all in one line is not always good.

chilly fractal
thorn flicker
#

just saw now.

chilly fractal
warm mason
granite badger
#
function test(p: Player, gID: string, t?: string, nC?: string) {
p.nameTag = `Β§cΒ§l${
 (p.getComponent('health').currentValue/2).toFixed(1)} Β§4Hearts
 Β§r${gemTypeColorCode[gID]}
(${gID.charAt(0)
.toUpperCase()
+gID.substring(1)})
\nΒ§r${t !== undefined ? `Β§g[Β§8${t.split(':')[1]}Β§rΒ§g] ` : ''}
${nC !== undefined ? nC.split(':')[1] : 'Β§7'}
${p.name}Β§r`;
}
gaunt salmonBOT
# granite badger ```ts function test(p: Player, gID: string, t?: string, nC?: string) { p.nameTag...

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 1 errors:

<REPL0>.ts:4:6 - error TS2304: Cannot find name 'gemTypeColorCode'.

4  Β§r${gemTypeColorCode[gID]}
       ~~~~~~~~~~~~~~~~

Lint Result

ESLint results:

<REPL0>.ts

1:10 error 'test' is defined but never used @typescript-eslint/no-unused-vars

wary edge
#

People do need to learn how to debug on their own.

chilly fractal
#

Yeah that's cuz debugger doesn't see it

granite badger
#

debugger isn't on strict mode

chilly fractal
#

I know the debugger won't catch it.

burnt musk
wary edge
chilly fractal
#

Cuz it can't possibly understand the value from just the code.

warm mason
#

Yes.. This bot often talks about errors that don’t exist.

thorn flicker
chilly fractal
chilly fractal
#

(In calm tone)

wary edge
thorn flicker
burnt musk
#

and... could an ActionFormData button be used to close the form?

wary edge
#

Using console.log, breakpoints, etc.

granite badger
#

Learn how to find and fix a problem in your code (without using my bot)

keen thorn
chilly fractal
# wary edge Like, actually learn how to debug.

To understand the bug from the content log? Ye I do that but just sometimes I can't possibly figure out what's the problem when it depends on what the value is and the value is from a database, and I'm sure that it's string.

warm mason
thorn flicker
wary edge
burnt musk
chilly fractal
#

Yeah that's the thing ima do rn, I'm seeing what gID is.

#

That doesn't mean I haven't made an error or something. It means I remember that I set it to string. Not that I logged it and found it was string.

#

We are gonna find out anyway, and I'm sure it's something stupid on my end.

distant tulip
untold magnet
#

guys

#

my bridge is broken again, i cant see the getComponent things

#

so

#

const enchant = itemStack?.getComponent("enchantable")?.getEnchantment;
if (enchant('silk_touch') { ,,, } is a thing?

chilly fractal
wary edge
#

Please just type it all in one message.

chilly fractal
wary edge
#

There we go, debugging.

dim tusk
untold magnet
#

i cant try it now

chilly fractal
#

I'll do it for u

untold magnet
#

the script isn't even 3% done

distant tulip
dim tusk
#

Is the bot back? I keep trying yesterday and it's not working lol

thorn flicker
granite badger
#

Guys, can we learn splitting your 40 page code into multiple functions, with each function does 1 task only please

thorn flicker
#

ive tested this

untold magnet
thorn flicker
wary edge
untold magnet
#

which version-beta is working?

wary edge
#

vscode supremacy.

granite badger
#

Also use vscode. Please

thorn flicker
wary edge
#

My function will do the work of 100 functions.

thorn flicker
wary edge
#

And it will all be on one line.

untold magnet
untold magnet
#

lemme show u

warm mason
untold magnet
thorn flicker
#

unless I missed a changelog and 1.16.0 became stable

granite badger
warm mason
wary edge
#

Beta, Preview, interchangeable.

wary edge
#

And I will also use vars and not let or const and name them by keyboard smashing.

warm mason
thorn flicker
wary edge
thorn flicker
wary edge
#

Context clues suggest that if they're talking about stable and beta, it means retail and preview.

thorn flicker
warm mason
#

||Someone wants to say that they want to work||

chilly fractal
#

@untold magnet [Scripting][error]-ReferenceError: Native function [ItemEnchantableComponent::getEnchantment] object bound to prototype does not exist.

chilly fractal
#

For example

untold magnet
#

wait a moment

#

const tag = itemStack?.getTags;
if (tag('minecraft:is_pickaxe')) { ,,, } is a thing

#

it should be fine with enchantments too

#

right?

untold magnet
thorn flicker
#

well it was a bad example

#

lol

granite badger
#

Native API doesn't allow that, normal javascript maybe

thorn flicker
#

you need to use the incldues function

warm mason
untold magnet
wary edge
thorn flicker
#

...

untold magnet
#

its just a test

thorn flicker
#

dude

#

just doitem.hasTag('tag')

dim tusk
dim tusk
untold magnet
#

guys, please understand, I'm not using that thing

#

its just to show i can use getEnchanment will work

distant tulip
dim tusk
#
import { world, EnchantmentType } from '@minecraft/server';

const player = world.getPlayers()[0];
const inv = player.getComponent('inventory')?. container;
const main = inv.getItem(player.selectedSlotIndex);

const enchant  = main?.getComponent('enchantable');
const get = enchant.getEnchantment({ id: 'fire_aspect' });
if (get) {

}```

Idk if this works, I forgor how to use this anymore
wary edge
#

Or something.

dim tusk
distant tulip
#

lol

chilly fractal
#

Just do ```js
const enchExits = (item, ench) => { return item?.getComponent('enchantable').getEnchantment(new EnchantmentType(ench)) !== undefined; });

wary edge
#

@untold magnetBut seriously dude, please use the docs.

untold magnet
thorn flicker
#

there's also hasEnchantment

warm mason
dim tusk
chilly fractal
untold magnet
dim tusk
dim tusk
#

Dude, there's al lot of docs

#

The Microsoft, bedrock, stirante and most importantly jayly

warm mason
wary edge
#

Stirante on top.

chilly fractal
#

Jayly on top.

warm mason
dim tusk
#

Microsoft on top.

thorn flicker
#

I use stirante

thorn flicker
warm mason
dim tusk
thorn flicker
dim tusk
warm mason
#

I'm surprised that people make some other documentation...

chilly fractal
#

Breakable by fist?

dim tusk
chilly fractal
#

Ohhhh

#

Niceeee

dim tusk
chilly fractal
#

So I can use my gem ability "Hot Hands" and turn it into ashs?

warm mason
chilly fractal
chilly fractal
untold magnet
#

const enchant = itemStack?.getComponent("enchantable")?.getEnchantment();
if (enchant?.type === 'silk_touch') { ,,, } should work?

chilly fractal
#

Bruh

#

Why?

#

JUST WHY?

untold magnet
#

im detecting multiple enchants

#

not only one

warm mason
chilly fractal
#

SO USE getEnchants()

thorn flicker
#

✌️

warm mason
untold magnet
#

if (isn't enchanted with silk touch) {
if (is enchanted with fortune) { ,,, }
}

chilly fractal
wary edge
#

Nested ifs.

fallow minnow
#

if isnt enchanted with silk && enchanted with fortune

wary edge
#

If personally there is numerous things in the silk touch, I would just do an early return.

dim tusk
#

That's all we want, it's for your own good.

#

That's a lot of emoji blud

#

Idk if this works lmao

if (['fortune', 'fire_aspect'].includes[item.getEnchantment()]) {}```
#

Just a hunch

warm mason
#
const multiEncFuncs = [{
  encs: ["silk_touch", "fortune"],
  func: (item => {
    // Code
  })
}]

function test(item) {
  for (let obj of multiEncFuncs) {
    if (obj.encs.every(encId => item.getComponent("enchantable").hasEnchantment(encId))) obj.func(item)
  }
}
dim tusk
dim tusk
dim tusk
chilly fractal
untold magnet
#

lemme just finish the script and show it, and u guys will show me what is unnecessary things i did.

warm mason
untold magnet
#

just my bridge-v2 is broken

wary edge
dim tusk
untold magnet
#

and i cant understand the getComponent section well

wary edge
warm mason
wary edge
#

It literally isn't that hard dude. We gave you the link.

dim tusk
#

Read docs, read docs, read docs, read docs, read docs....
-# reference.

warm mason
dim tusk
untold magnet
#

im asking about the only thing is broken on the website im using and i have no idea how it worksjoeshrug

warm mason
dim tusk
#

I mean, learn script without help of people and docs let's see

untold magnet
dim tusk
#

Is your script now done my good sir?

untold magnet
#

na

fallow minnow
#

honestly just basic js/ts knowledge will help u understand

#

being able to read what is accepted into arguments is a big help

untold magnet
warm mason
fallow minnow
#

seems like you are

untold magnet
fallow minnow
#

simple

#

bridge is for beginners

#

if youre not a beginner, why use

untold magnet
thorn flicker
#

I use bridge

fallow minnow
#

i think bridge is quite doodoo

thorn flicker
#

okay

fallow minnow
#

useful for beginners

warm mason
untold magnet
fallow minnow
#

vscode?

untold magnet
fallow minnow
#

then...

unique dragon
#

certainly, good for beginners, but in this case, for scripting api, it's better to use vsc

fallow minnow
untold magnet
#

im on mobile

fallow minnow
#

i use vscode + ts

thorn flicker
untold magnet
fallow minnow
#

oh

thorn flicker
#

should've mentioned that

fallow minnow
#

well coding on mobile is 10x harder in general

#

even if you're using bridge

thorn flicker
#

can confirm that, I have a buddy that does this on mobile.

warm mason
#

Just download any code editor and that’s it.

fallow minnow
#

it was such a pain

#

it was over a year ago and it was with the app "koder"

thorn flicker
#

json ui makes my brain hurt

fallow minnow
#

i had an xbox and an iphone

#

i would upload the pack to mediafire and download it on my xbox

warm mason
#

I make addons on my phone, although I have a computer...

fallow minnow
unique dragon
#

acode bao_icon_particles

thorn flicker
untold magnet
#

just to make sure im going right

  const enc = itemStack.getComponent('minecraft:enchantable');
  let silkTouch = enc?.getEnchantment('silk_touch');
  let fortune = enc?.getEnchantment('fortune')?.level;```is it right? just to make sure.
burnt musk
#

is there any way to run something (e.g. some command) when they open certain action form page?

thorn flicker
#

well

#

I would personally remove '.level' and just get the property when checking it in a conditional statement

unique dragon
untold magnet
warm mason
unique dragon
#

nice /super comand

#

xd

warm mason
thorn flicker
#

also stop using commanddsss

fallow minnow
#

anyone have some ideas on how i would "pull" players towards a location?

thorn flicker
#

player.sendMessage('SUPER DUPER BUTTON')

warm mason
thorn flicker
fallow minnow
#

i dont like mat

#

h

unique dragon
#

lol

thorn flicker
fallow minnow
#

its for my whirlpools

#

if they are in water and near a whirlpool it can sometimes suck them into it and they cant swim out of it

burnt musk
#

@unique dragon @warm mason will try 😁

thorn flicker
#

is it an entity?

fallow minnow
#

the whirlpool is an entity

thorn flicker
warm mason
fallow minnow
thorn flicker
fallow minnow
#

hm

warm mason
thorn flicker
#

I was thinking of apply impulse

#

mb

warm mason
thorn flicker
warm mason
#

ok

fallow minnow
burnt musk
#

imported UIManager and didUIManager.closeAllForms(sourceEntity);

#

but when it runs it says it's not a function ([Scripting][error]-TypeError: not a function at <anonymous> (main2.js:1415))

#

please what am I doing wrong?

#

I tried to run the function through an UIManager object (through new UIManager()), but then it says No constructor for native class 'UIManager'

#

UIManager doesn't have any constructor so idk what to do

#

I'm pretty new with this πŸ˜ͺ

distant gulch
#

the instance of UIManager is uiManager

untold magnet
#
if (id?.matchAll('normal:ore', 'deepslate:ore')) {eDrop(block, loc, fortune, 'base:drop'); if (Math.random() <= 0.25) eDrop(block, loc, fortune, '25%:drop')};```does it have any issues?
burnt musk
distant gulch
#

No, the constructor of UIManager is private, so you only need to import uiManager from server-ui

burnt musk
#

already imported it at the beginning of my .js file

#

import { ActionFormData, UIManager } from "@minecraft/server-ui";

untold magnet
distant gulch
burnt musk
#

it works now, thank you @distant gulch πŸ™Œ πŸ™Œ

last latch
buoyant canopy
#

is it possible to get the type id of a falling block entity?

#

and i mean by that the typeId of the block that is falling, because the typeId of the entity is minecraft:falling_block, and that's not really useful

random flint
#

no

near siren
#

Is there a way to get the face of a block you mined, or do I have to jerry rig something to find out?

neon thunder
#

you'd need to check in before break block the head direction of the player perhaps?

slow walrus
#

should be on the event args

neon thunder
#

Does anyone know about afterEvents.playerInputPermissionCategoryChange? Why isn't it being fired in 1.21.44 when its documented? Do I have something wrong or is this expected behaviour?

near siren
slow walrus
neon thunder
#

you should be able to figure out the player's facing by examining their head

slow walrus
#

you'd have to do some maths yeah

near siren
#

Welp...math I go

wary edge
#

@near siren
#1067535608660107284 message

#

Not necessarily accurate for blockFace but at least you can get the players facing direction. Alternatively you could do entityHitBlock.

near siren
#

The god himself has mentioned me, thank you. I'll see what I can do

rigid torrent
#

How can I cancel block placement in stable?

dim tusk
rigid torrent
#

In latest stable or preview?

dim tusk
warm mason
dim tusk
warm mason
#

You need to use playerInteractWithBlock

dim tusk
rigid torrent
warm mason
#

No. If you need to check only specific blocks, then you can simply compare the ID of the item in the player’s hand

rigid torrent
#

No I need everything

#

I need to cancel placement of any block

warm mason
#

Then check if the item ID is in the list of block types

rigid torrent
#

Will give it a shot, thanks!

eternal eagle
#

Is there a way to get block light level via code yet

#

or will it be implemented

eternal eagle
#

sadge

#

is it on the roadmap of things to add

warm mason
eternal eagle
#

gonna have to wait until the 2025 api qna

fiery solar
# eternal eagle Is there a way to get block light level via code yet

Not sure if you're asking for a way to get the light_emission value of a block, or just the light level at a particular location. (I guess there's not too much difference since you can find the former by placing a block in the world and testing the light at that location)

There's no native API call for this, but you can get the light level by using an invisible temp entity that triggers an event based on a molang query for the light level. I just posed an example: #1306499809451966514 message

eternal eagle
#

ty

untold magnet
#

guys, I'm too curious if i can do this thing:

having an array that has multiple different blocks types, inside of 'playerBreakBlock' component theres a tiny system that requires the blocks ids in the array, i can do that simply by using 'array.includes' but thats not what i need specifically,
I'm wondering if i can use the Ids inside of that array in a specific way.
like giving each ID in the array a number
instead of using this:
+
if (eBlock.type.id === 'block:one') aFunction(eBlock, 'block:one');
if (eBlock.type.id === 'block:two') aFunction(eBlock, 'block:two');
+
i can make it simpler by using the array number,
like this:
if (id1, something) aFunction(eBlock, id1)
idk if i explained it right but i hope u guys
-
understand what im asking for.```so i dont have to write the same Id again and again
#

if it is possible, show me how bec i need it.

slim spear
#

Do you want to set specific functions to specific blocks but have a handler for it?

untold magnet
#
const array = [ 'block:one', 'block:two' ]
// playerBreakBlock
if (eBlock.type.id === 'block:one') aFunction(eBlock, 'block:one');
if (eBlock.type.id === 'block:two') aFunction(eBlock, 'block:two');```i dont wanna do this if i can use the ID directly from the array
slim spear
#
const array = ['block:one', 'block:two']

if (array.includes(eBlock.type.id)) aFunction(eBlock, eBlock.type.id)
#

?

untold magnet
#

if i can use a method that will make me able to use the IDs directly from the array will be more efficient

untold magnet
#

i dont want to write the block ID multiple times,

slim spear
#
const array = ['block:one', 'block:two']

const id = eBlock.type.id
if (array.includes(id)) aFunction(eBlock, id)
untold magnet
#

like giving the array multiple sections, each section will have it own ID, and i can use that ID to run the function and the ID will take the blocks ID inside it

slim spear
#

ohhh

#

okay

#
const array = [
     {
          id: 'block:one', 
          code: () => {world.sendMessage('block one')}
     }, 
     {
          id: 'block:two', 
          code: () => {world.sendMessage('block two')}
     }
]


const found = array.find((f) => f.id === eBlock.type.id)
if (!found) return
found.code(found.id)
#

?

#

still kind of confused

#

ngl

#

Also idk if I wrote it correctly, am on phone rn

untold magnet
slim spear
#

bro has not seen how I code ig

#

I use that array stuff all the time

untold magnet
slim spear
#

no it's find

#

used it in de trident template too

untold magnet
#

or array.findIndex

untold magnet
slim spear
#

no?

untold magnet
slim spear
#

const tridentData = CustomTridents.find((f) => f.itemID == item.typeId)

#

I've never used findIndex

#

only find

untold magnet
#

GUYS, do not tell me to use docs bec array things aren't available in docs i know

slim spear
dim tusk
slim spear
# slim spear ```js const array = [ { id: 'block:one', code: () => {...

full thing

const array = [
    {
        id: 'block:one',
        code: (id: string) => { world.sendMessage('block one') }
    },
    {
        id: 'block:two',
        code: (id: string) => { world.sendMessage('block two') }
    }
]

world.beforeEvents.playerBreakBlock.subscribe((data) => {
    const eBlock = data.block
    const found = array.find((f) => f.id === eBlock.typeId)
    if (!found) return
    found.code(found.id)
})

in ts though, got on my laptop now

untold magnet
#

#1306560102668435457bao_icon_entities

wintry bane
#

Quick question, what do you guys use for scriptevents? Switch? Ifs? or Objects?

slow walrus
wintry bane
slow walrus
#

yes

#

the 3rd thing you're doing in the screenshots is pretty much just a overcomplicated version of that

simple zodiac
# wintry bane Quick question, what do you guys use for scriptevents? Switch? Ifs? or Objects?

Nah I think making a wrapper arround a single listener is the best as it is less calls from native. Using a lookup is always faster then if statements. Both switch and objects can do that. But the way you implemented it with the .forEach it is quite inefficient. The best way would be to have an object or a map where the id is the key and the value your function. This would ensure a constant lookup time. But tbh it only matters with big data sets here it will not matter like at all unless you are running a lot of them in a tick

wintry bane
#

I see

slow walrus
#

native listener iteration is faster than in the JS runtime

simple zodiac
#

I do not belive that. You'd have to drop the benchmark

fiery solar
fiery solar
#

@wintry bane The answer to this question is definitely objects, but not in any of the ways you have in the screenshots. You don't want to use arrays at all. You want an object where the key is exactly the script event id and the value is the function you want to call.

const events = { 
"id:event" : functionA,
"id:eventb" : functionB
}

Then in the script event you do

events[e.id]()

To call it

fiery solar
slow walrus
warm mason
#

What are you discussing?

slow walrus
#

second one is gonna be faster every time

warm mason
#

I think a single subscription is only needed when you want to track each subscription, for example, to make fake event calls

slow walrus
#

sure but it'll be slower

warm mason
#

If you don't have 500 events, that's fine.

fiery solar
slow walrus
#

in the screenshots

slow walrus
#

average time complexity is actually O(1+n/k) where k is the size of the hashtable

remote oyster
#

Big O Notation 😁

A developers friend when one has good relationship with it.

subtle cove
#

ngl, i still forget what those hashing methods are and just proceed with whatever comes up to mind

untold magnet
#
  const gM = player.getGameMode('creative');
  if (gM) return;```should return when the player is creative?
untold magnet
wary edge
#

Sure, whatever.

idle dagger
#

Why playerPlaceBlock beforeEvents was working on armor stand before but now it’s not?

untold magnet
fallow minnow
#

No it’s because when I bought the White House I told them to change it

idle dagger
distant tulip
wary edge
#

Are you sure it wasn't another event triggering it?

idle dagger
idle dagger
distant tulip
#

huh

fallow minnow
fiery solar
# slow walrus I was talking about the case that the original asker showed

I don't think I follow what you're saying (maybe we're agreeing with each other?), there were 4 screenshots posted and none of them had multiple subscriptions in them.

Script events don't support listening to a specific "namespace:id" combination, so you can either:

  1. have each subscription check the event id with an if statement, in which case we're checking the event id in the javascript context and not saving any CPU cycles (still looking at O(n) and it's no faster than just using a bunch of if statements):
  system.afterEvents.scriptEventReceive.subscribe(
    (e) => {
      if (e.id === "mynamespace:function1") {
        /** Logic for script event 1 */
      }
    }
  );

  system.afterEvents.scriptEventReceive.subscribe(
    (e) => {
      if (e.id === "mynamespace:function2") {
        /** Logic for script event 2 */
      }
    }
  );

// ...
  1. Or are you suggesting that all of the script events would have a different namespace and we would be filtering by namespace and ignoring the event id when making the subscription like this where /scriptevent function1:aaa would hit the same listener as /scriptevent function1:bbb?
  system.afterEvents.scriptEventReceive.subscribe(
    (e) => {
        /** Logic for script event 1 */
    },
    { namespaces: [`function1`] }
  );

// ...

Because I just tested both option 1 and 2 above and with 10,000 script event listeners and option 1 is 10,000 times slower than the method I suggested with a Map, as expected. And option 2 (letting the game engine handle the filtering of namespaces) is a little faster than option 1, but still 2,000 times slower than routing with a Map.

buoyant canopy
#

can we make the player swing

#

?

distant tulip
buoyant canopy
#

do you have one?

untold magnet
#

uh, guys..
im using this method for damaging my tools:

function dmg(itemStack, player, enc) {
  if (!enc) dur(itemStack, player);
  if (enc === 1 && Math.random() >= 0.25) dur(itemStack, player);
  if (enc === 2 && Math.random() >= 0.34) dur(itemStack, player);
  if (enc === 3 && Math.random() >= 0.49) dur(itemStack, player);
}```so, there's a more efficient way to do it using a switch case or syntax thing, so can u guys edit it?
distant tulip
#

@buoyant canopy

#

you may need to edit it for first person camera

untold magnet
buoyant canopy
buoyant canopy
distant tulip
buoyant canopy
distant tulip
#

i just did
source.playAnimation("animation.steve.swing")
and it worked fine

buoyant canopy
#

i am using it in a playerInteractWithBlock beforeEvent(system.run())

distant tulip
#

check the third person camera?

buoyant canopy
#

i will send a screenshot

distant tulip
buoyant canopy
#

i get the message but not the animation

distant tulip
#

weird
let me try again

buoyant canopy
distant tulip
#

maybe i need to add the item bone there

buoyant canopy
#

for me, it doesn't even work in 3rd camera

distant tulip
#

do you have another animation or something?

buoyant canopy
#

i think i figured it out

#

nevermind

#

so when i run the command you used in the video it works

#

but not when i call it in the script

#

it does work even without the parameters

#

the command that is

distant tulip
#

it work with script too
or i think so?

buoyant canopy
#

it works! i don't know what i did, but it works now???

distant tulip
buoyant canopy
#

but first person is still broken

distant tulip
#

it need the item bone to move
let me try making it do so

buoyant canopy
distant tulip
buoyant canopy
#

because i am in survival bone meal is consumed and it acts like it's animated

distant tulip
buoyant canopy
#

it's completely still in creative tho

#

it's kinda a mockup fix, but i will go with it, thanks a lot for helping me today!

distant tulip
#

your wlc

distant tulip
buoyant canopy
distant tulip
#

it is not

untold magnet
#
world.beforeEvents.playerBreakBlock.subscribe(({ itemStack, block, cancel }) => {
  const { x, y, z } = block?.location;
  const silkTouch = itemStack?.getComponent('minecraft:enchantable')?.getEnchantment('silk_touch');
  if (silkTouch) if (block?.typeId?.startsWith('exe:') && block?.typeId?.endsWith('_ore')) { system.run(() => {block?.dimension.runCommandAsync(`fill ${x} ${y} ${z} ${x} ${y} ${z} air destroy`)}); cancel = true};
})```this is not cancelling the block distraction, why?
#

specifically cancel = true isn't working

untold magnet
distant tulip
untold magnet
#

i want to cancel the block break

distant tulip
#
world.beforeEvents.playerBreakBlock.subscribe((event) => {
  const { itemStack, block } = event
  const { x, y, z } = block?.location;
  const silkTouch = itemStack?.getComponent('minecraft:enchantable')?.getEnchantment('silk_touch');
  if (silkTouch) if (block?.typeId?.startsWith('exe:') && block?.typeId?.endsWith('_ore')) { system.run(() => {block?.dimension.runCommandAsync(`fill ${x} ${y} ${z} ${x} ${y} ${z} air destroy`)});
event.cancel = true};
})```
untold magnet
#

cancel = true was working before

buoyant canopy
remote oyster
untold magnet
#

anyways this will no longer happen,

unique yoke
#

compiler bot is just deadass not working for me

unique acorn
#

so wait for jayly to fix em

steady canopy
#
{
    "format_version": "1.20.0",
    "minecraft:item": {
        "description": {
            "identifier": "item",
            "category": "Items"
        },
        "components": {
            "minecraft:max_stack_size": 1,
            "minecraft:icon" : {
                "texture": "item"
            }        
        }
    }
}

Does someone know why when i try to set dynamic properties in my item it says "Cannot set dynamic properties on stackable items" but this item isn't stackable, it's max _stack_size is 1 and it was working good before.