#Script API General

1 messages ยท Page 41 of 1

dull shell
#

no that was my entire js file

slow walrus
#

what the

#

where are your if statements

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

/** @type {import("@minecraft/server").BlockCustomComponent} */
const CreativeModeOnlyBlockComponent = {
    onPlayerDestroy(event) {
        if (event.block.typeId === "jay:coal_ore" && event.entity.typeId === "minecraft:player") {
            entity.runCommandAsync("execute @s ~~~ say broke coal ore");        
        }
    }
}
#

plus that event is wrong anyway

#

it's player not entity

#

and block doesn't exist

winter plaza
#
import { world } from "@minecraft/server";

world.afterEvents.itemUse.subscribe(event => {
  const itemStack = event.itemStack;
  if (itemStack.typeId === "minecraft:diamond_sword") {
    const itemData = itemStack.getComponent("minecraft:display_name");
    if (itemData) {
      itemData.setLore(["Custom Description 1", "Custom Description 2"]);
    }
  }
});
#

help

slow walrus
#

it should be like this:

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

/** @type {import("@minecraft/server").BlockCustomComponent} */
const CreativeModeOnlyBlockComponent = {
    onPlayerDestroy(event) {
        if (event.destroyedBlockPermutation.type.id === "jay:coal_ore") {
            event.player?.runCommandAsync("say broke coal ore"); 
        }
    }
}
#

@dull shell

dull shell
#

oooo i forgot about if statments

#

sorry im new to js

dull shell
#

yeah its still not working im not sure

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

const CreativeModeOnlyBlockComponent = {
    onPlayerDestroy(event) {
        if (event.destroyedBlockPermutation.type.id === "jay:coal_ore") {
            event.player?.runCommandAsync("say broke coal ore"); 
        }
    }
}```
#

i removed the thing up top

slow walrus
#

did you initialize it?

#

what are you trying to do anyway

random flint
#

cache if the position xyz in that location was a cake

dull shell
dull shell
dull shell
random flint
# dull shell wdym

Did you register the custom component? Did you use it in your block.json?

slow walrus
# dull shell wdym
import { world, GameMode } from "@minecraft/server";

const CreativeModeOnlyBlockComponent = {
    onPlayerDestroy(event) {
        if (event.destroyedBlockPermutation.type.id === "jay:coal_ore") {
            event.player?.runCommandAsync("say broke coal ore"); 
        }
    }
}

world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
    blockComponentRegistry.registerCustomComponent(
        "jay:coal_ore_component",
        CreativeModeOnlyBlockComponent
    )
})

then in your block.json add

"minecraft:custom_components": [
    "jay:coal_ore_component"
]
dull shell
#
{
    "format_version": "1.21.40",
    "minecraft:block": {
        "description": {
            "identifier": "jay:coal_ore",
            "menu_category": {
                "category": "construction", 
                "is_hidden_in_commands": false
            }
        },
        "components": {
        },
        "minecraft:custom_components": [
        "jay:coal_ore_component"
        ]
    }
}```
random flint
dull shell
#

amen ๐Ÿ™

#

thank you guys sm

#

so then to add more just keep copy and pasting it?

#

then changing it from jay:coal_ore to wtv

distant gulch
#

Is it possible to attach a sign to a wall?

chilly fractal
#

Now I'm 100% sure it's permutation

#

Yessss! This is my time to shine!

distant gulch
#

however ```js
export type BirchStandingSignStates = Pick<BlockStateSuperset, 'ground_sign_direction'>;

#

Dont seem to support anything but the direction itself

#

I had to settle on this

#

):

chilly fractal
#

Nuh uh

distant gulch
chilly fractal
#

Noooooo!!!! Why not let me resolve it for you??? Why resolve it (fades away like Thanos even tho he not evil)

distant gulch
#

what do you suggest?

chilly fractal
#

I mean, could it work? ```js
block.setPermutation(block.permutation.withState("cardinal_direction", "west"));

distant gulch
#

ill need to try that

chilly fractal
#

I gtg cuz it's 5 am here

#

I just fell asleep and I now woke up randomly

distant gulch
#

good night

sterile epoch
#

does anyone know what reach the player has since ik it changes depending on if you're sprinting, walking or still

chilly fractal
dim tusk
chilly fractal
#

Lmao "minecraft:display_name" maybe in a different universe after Flashpoint occurs lol

#

(You'd only understand if you watched the flash up to season 4 I believe)

#

item.nameTag & item.setLore have been real quiet since his code appeared fr

#

Worst part is he is setting the lore to the component (that does not exist)

dim tusk
#
import { world } from "@minecraft/server";

world.afterEvents.itemUse.subscribe(({ source, itemStack }) => {
  const equipment = source.getEquipment('equippable');
  if (itemStack.typeId === "minecraft:diamond_sword") {
   itemStack.setLore(["Custom Description 1", "Custom Description 2"]);
   equipment.setEquipment('Mainhand', itemStack);
  }
});
chilly fractal
#

I don't think lore needs you to regive the the item,... but whatever.

dim tusk
#

I don't know tbh, because I rarely use lore ask @valid ice he's addicted to it

chilly fractal
#

I mean, iirc I think nameTag & lore don't need you to regive the item. Other things like enchants & durability and stuff like that requires regiving the item.

#

I used it not long ago and I didn't need to regive the item.

subtle cove
#

ContainerSlot ItemStack difference

dim tusk
chilly fractal
#

Not sure tho

dim tusk
#

It's like getEquipmentSlot and getEquipment

chilly fractal
#

Moyang be confusin' sometimes fr

chilly fractal
dim tusk
#

Imma test it really quick I'm on my phone so it's good

subtle cove
#

ContainerSlot is the present instance of the slot like slotIndex 0

subtle cove
#

ItemStack is a clone of an item

chilly fractal
#

K....?

#

I didn't ask for the difference........ I know that they are different.................. I thought you were asking so I gave you my assumption.

#

Ima go now cuz I gotta learn some good'ol heavy duty backend. (Php). Why do I call it that? Cuz it's syntax makes -1% sense! ๐Ÿ˜€

dim tusk
#

And..... It doesn't work without setting the item back to the slot

#

I luv how I can open mc fast but my internet is as slow a turtle

subtle cove
#

cus its all ItemStack...

dim tusk
subtle cove
#

ok

distant gulch
#

getItem, getEquipment Method:
Purpose: Retrieves a read-only copy of an item's data
Behavior: Provides a snapshot of the item without enabling direct modifications
Recommended Use: When you need to inspect or reference item properties without altering the original inventory item

getSlot, getEquipmentSlot Method:
Purpose: Allows direct modification of an item's data within the inventory
Behavior: Returns a ContainerSlot instance that enables immediate and persistent changes
Recommended Use: When you need to update, replace, or manipulate the item in its original inventory slot

Key Distinction: getItem offers a non-destructive, read-only view, while getSlot provides a direct interface for inventory item manipulation.

Always choose the appropriate method based on whether your intention is to read or modify inventory items

dim tusk
#

Unnecessary butt k

distant gulch
#

This is essential: you should never retrieve a copy of an item, modify it, and then put it back

dim tusk
#

Are you saying when you just want to set a lore into an item you literally need to use getEquipmentSlot or getSlot to such a simple thing?

tawny jungle
#
                    if (item) player.dimension.spawnItem(item, player.location)```
why is this giving me a bunch of items?
dim tusk
#

Even if you put 1 only but you run continuously it will give you more than that

tawny jungle
#

just on click in playerInteractWithBlock

dim tusk
tawny jungle
#

oh yeah sry

#
    const blockAbove = block.above();
    const blockFaceValue = blockAbove.permutation?.getState("sci:block_face");
    const position = redstoneOreParticleSpawnPositions[blockFaceValue];
    const playerMainHandSlot = player.getComponent("equippable").getEquipment("Mainhand");
    const honeyFilled = block.permutation?.getState("sci:honey_filled")
    system.run(() => {
        if (block?.typeId === "sci:bee_nest_mini" && playerMainHandSlot?.typeId === "minecraft:honey_bottle" && honeyFilled === false && player.isSneaking) {
            block.setPermutation(block.permutation.withState("sci:honey_filled", true));
            if (player.getGameMode() === "survival") {
                if (playerMainHandSlot.amount === 1) {
                    player.getComponent("equippable").setEquipment("Mainhand", new ItemStack("minecraft:glass_bottle", 1));
                } else {
                    itemStack.amount--;
                    player.getComponent("equippable").setEquipment("Mainhand", itemStack);
                    const item = player.getComponent("inventory").container.addItem(new ItemStack("minecraft:glass_bottle", 1))
                    if (item) player.dimension.spawnItem(item, player.location)
                };
            };
        }
        if (block?.typeId === "sci:bee_nest_mini" && playerMainHandSlot?.typeId === "minecraft:glass_bottle" && honeyFilled === true) {
            block.setPermutation(block.permutation.withState("sci:honey_filled", false));
        }
    });
});
dim tusk
tawny jungle
#

i stole it from something else in my script

#

i was feeling lazy

#

but also it ensures it still runs even when it is the last item in the slot

distant gulch
ruby haven
#

Is there a way to kill a player with a minimum health component through scripts cause I tried overding that component through json but it didn't work

scarlet sable
#

what allows a mob to break blocks in a script?

scarlet sable
#

for anyone looking fo the answer in the future it's minecraft:break_blocks

scarlet sable
#

mb I used the wrong term

dim tusk
dim tusk
buoyant canopy
#

so when you define a really really large variable in the beginning of a script, and rarely use it, is it filling up a chunk of memory all that time for no reason?

ruby haven
burnt robin
#

please someone explain how this makes sense

#

ughhh

#

lemme fix the size

dim tusk
dim tusk
burnt robin
#

(its sending what it logs without the number just the array)

distant tulip
dim tusk
burnt robin
buoyant canopy
# distant tulip yep

is it better to load it at the beginning of a script or load it once you need it?

#

let's say you need to access it 10 times in one session but most of the time you won't need to access it.
isn't loading it and unloading it 10 times bad for performance?

distant tulip
#

in general it is better to pre-load stuff that may effect performance

buoyant canopy
#

if i preload everything, i am putting unnecessary load on the memory, if i don't, i am adding extra work for the CPU

distant tulip
#

what variable are we talking about here

buoyant canopy
warm mason
buoyant canopy
#

for an achievements system

buoyant canopy
warm mason
buoyant canopy
distant tulip
#

even a 1mb shouldn't be a problem to preload it

buoyant canopy
#

i also have another file for a similar system that is 66 kilobytes

buoyant canopy
distant tulip
#

no

buoyant canopy
#

is the file size the amount of memory used?

buoyant canopy
#

or does it get compressed?

buoyant canopy
warm mason
#

Memory is just variables. You can create a 10 line code that creates an array of 1,000,000 objects that takes up half the memory

warm mason
buoyant canopy
#

let's say it's just a constant that doesn't change or get defined again throughout the process. will it consume exactly 49 kilobytes of memory

warm mason
buoyant canopy
#

only properties

warm mason
buoyant canopy
#

but in general it stays constant?

warm mason
#

if this is not true/false then there are methods

buoyant canopy
buoyant canopy
warm mason
#

Modern amounts of RAM are sufficient to accommodate your variable, but it seems to me that the debugger may complain about using too much memory

#

What does this variable look like?

distant tulip
#

you can use process.memoryUsage() in node js to get the memory usage

warm mason
buoyant canopy
# warm mason What does this variable look like?

well it's not an array anymore, i change it into a string for ease of editing, and i have a function that converts it back into an array, so it's hard to let how does it look when it's loaded

#

but if i have to guess it looks like this: js [ { id: string, name: string, icon: number|string, require: [string] reward: undefined|string conditions: [string] } ]

warm mason
#

In short. Even if you have problems using memory. Do you have another option to do this?

buoyant canopy
#

what do you mean?

warm mason
#

The fact that you are trying to solve a problem that has no solution. You're already using the best option

buoyant canopy
#

i figured preloading large constants is best for cpu, but i thought the game was smarter for dealing with memory

#

but if 50kb is nothing for modern RAMs I don't really care much

warm mason
distant tulip
#

it is not 50kb
memory storage is not same as disk
but it shouldn't be a problem in this small scale

buoyant canopy
#

one thing i am afraid of, when i import that constant to different scripts, does it take a chunk of memory for each one of them?

distant tulip
#

not sure how the import work tbh
let me look into it

buoyant canopy
#

i think it does, because if i mutate an imported object or array, it obviously doesn't affect other scripts

distant tulip
#

@honest spear do you have any knowledge regarding this?

honest spear
#

do you think you can provide me more context

#
  • whats you want to achieve
  • whats is unexpected
  • why do you think it should happen in different way
honest spear
#

same file imported from different files has same isntance

#

so no copy of the module is created

#

if thats what do you mean

buoyant canopy
distant tulip
#

he is importing a variable from another file and he is asking if calling that variable use any memory or just refer to the same

honest spear
#

its freezed

buoyant canopy
#

a mutated version for each file importing it

honest spear
buoyant canopy
#

...

#

let's say i have a file containing one exported object.
and i have 10 other scripts importing that same object.
now there is 10 mutated objects,
how are they handled by memory?

honest spear
distant tulip
#

they are probably referring to the same obj that got exported

honest spear
#

well there could be some cases when exported value is different, but only when you reassign that exported object

buoyant canopy
honest spear
#

so if exported object is "export const" then there is only one object in total of that type

#

also you can just test it if you don't believe me

#

ยฏ_(ใƒ„)_/ยฏ

buoyant canopy
#

i Know that, i will try to explain what i mean by an example:
when i import the object {fish: "large" }
and then mutate it to {fish: "medium" } in one file, and then i import it to another file, and mutate it to {fish: "samll" }
how does the memory look like at this point

honest spear
distant tulip
#

you are editing the same variable

honest spear
#

nah

#

you are editing the same obejct

buoyant canopy
#

i am not worried about the original object, i believe you that it doesn't get mutated

honest spear
#

but mutability doesn't means its not the same object

#

here is example

buoyant canopy
#

my concern is the memory, does it have copies of it or not?

honest spear
#

pointer for that object is the same

#

but there were some copies bc you manipulated with string

#

and strings are bytes in memory

buoyant canopy
#

so in general it's best if i don't import large objects to multiple files.

honest spear
#

no

#

in general don't use large strings

#

don't*

#

object in memory has dynamic size

#

and object pointer it self is relatively small

buoyant canopy
#

computer memory is a real pain, good thing we don't have to worry about it in js

#

and other high level programming languages

honest spear
#
let data1 = {test: "test"};
let data2 = data1;

data1.test = 5;
console.log(data1); // {test: 5}
console.log(data2); // {test: 5}

the object is the same even you you changed the property

honest spear
#

ยฏ_(ใƒ„)_/ยฏ

distant tulip
#

lol

buoyant canopy
honest spear
#

np if you have any more questions just ping me anytime

buoyant canopy
#

these questions come to me while coding and i can't help but feel bad for not optimizing something that's really obvious

buoyant canopy
honest spear
#

๐Ÿ’€ node_modules ๐Ÿ’€

valid ice
#

while (true) Clueless

honest spear
warm mason
honest spear
valid ice
#
int *ech = (int *)0x0;
*ech = 0;
``` ![Clueless](https://cdn.discordapp.com/emojis/1189130963209429073.webp?size=128 "Clueless")
wary edge
honest spear
valid ice
#

if (goingToCrash) return false;

honest spear
#

||There are no other languages than JS in this universe||

valid ice
#

False! Polish exists

honest spear
warm mason
honest spear
honest spear
warm mason
#

#off-topic

#

Or write to Microsoft support

scarlet sable
#

oh ye mb

gaunt salmonBOT
#
Debug Result

JavaScript/TypeScript code blocks not detected in [message](#1067535608660107284 message).
You can either send the script in code block highlighted in JS format:

โ€‹`โ€‹`โ€‹`js
world.sendMessage("Hello World");
โ€‹`โ€‹`โ€‹`

Or Send an attachment end in .js to debug the file.

burnt robin
buoyant canopy
distant gulch
#

nvm its c++

distant tulip
distant tulip
distant gulch
vital halo
#

how do i see what item the player is holding? i'm trying to hook onto playerBreakBlock to see if they have certain equipment on

warm mason
vital halo
#

thank you so so much ^^

#

i do feel kinda bad asking so many questions lmao

#

i appreciate all the help i'm being given

burnt robin
neat hound
#

WTF... faceLocation in PlayerInteractWithBlock is Vector3 Absolute world position and faceLocation in PlayerPlaceBlock is the final delta from center of block. Thus making my class useless for what I need... I can fix, but dang...

#

No wonder this stuff is still beta.. and they did not even provide faceLocation in the blockRegistry version of place block, which would be dope

wary edge
valid ice
neat hound
#

Can't fix the not providing it for custom components tho.. which is why I have to do my slabs in the regular events... (cause I am providing vertical positions)

distant tulip
wary edge
neat hound
#

Slab, that can be placed horizontal or vertical and depending on where you click on a block. So think of a block divided as a 4x4 grid... so that the middle means flat - just use the block face, but the edges can place it perpendicular, etc.....

I've made my block with with Interact (1st time, cancelling all tho), but there is a weird visual lag when placing a block, like it undoes a regular placement... I can see it.

wary edge
#

That seems like a simple thing. Just cancel block placement via beforeOnPlayer place custom component. Grab interaction faceLoc -> set block.

neat hound
#

I did

#

I am testing via using the block placement right now... I will change it back to the other to show later... I made a class that can take either event and pull out the information and configure, so there is one function to do the work either way.

#

But still the blockRegistry component for placing a block does not have faceLocation at all... like they forgot (or did not remember that I think outside of all the boxes)

wary edge
wary edge
#

Ideally...this all would have been a block trait.

neat hound
#

I use the block trait... my strictly vanilla version does not need the scripts at all... whatever block face you stick it on is where it goes, vertical or hoizontal

#

but in order to do like real slabs I can add the vertical half... but for the vertical slabs, I need a non-provided horizontal-half

#

thus, I need face location to tell me where they clicked and I can figure it out myself

#

and then for special placing, I use the information of where clicked and the block-face trait of the slab they clicked on (if added to another of same type) for more fun stuff

#

Believe it or not, this is all for my Auto-Sifter Add-on.... cause can sift concrete powder... and powder needs to become concrete if water touches... thus you can make slabs from 1 to 15 height... so need a way to place them... I am loving workin on this tho

#

After working... will re-use code for my actual more-slabs add-on

alpine nebula
#

Can I somehow load unloaded chunks using coordinates of block in it?

fiery solar
vital halo
#

Is there a way to drop items with scripting?

#

I imagine

#

I also need to know about summoning entities with this but-

#

I have been looking a lot at the documentation and that's given me many answers, but I don't know what I don't know and am unsure where to begin

distant tulip
distant tulip
vital halo
#

thank you so so much

dim tusk
#

I want a function to return true otherwise false if the player is holding an item with data but idk how, I don't want to use tags for thsi

#
function waterBottle(player) {
   try {
      player.runCommand('excute at @s[hasitem={item=potion,location=slot.weapon.mainhand,data=0}] run ...');
      return true;
   }
}```
#

Kinda like this lol

#

I just want it to return true or false lol

distant tulip
#

just make a new itemstack and use isStackableWith

dim tusk
dim tusk
#

I'm lying that I'm lazy, I don't really know how to use that shi at ALL...

tawny jungle
#

how laggy are permutations?

#

like a lot of them

#

like 200,000

#

wait

#

wrong channel

wary edge
tawny jungle
#

i see

#

thanks

distant tulip
# dim tusk I'm lying that I'm lazy, I don't really know how to use that shi at ALL...
import { Player, ItemStack } from "@minecraft/server";

/**
 * Checks if the given player is holding a water bottle.
 * @param {Player} player Player to check.
 * @returns {boolean} True if the player is holding a water bottle.
 */
function isWaterBottle(player) {
    const heldItem = player.getComponent("inventory").container.getItem(player.selectedSlotIndex)
    if(heldItem?.typeId == "minecraft:bottle") return false
    const bottle = new ItemStack('minecraft:bottle')

    //clear unnecessary data that will interfere with isStackableWith
    heldItem.nameTag = undefined
    heldItem.setLore()
    heldItem.clearDynamicProperties()

    if(heldItem.isStackableWith(bottle)) return true
}
#

wait... is minecraft:bottle for empty bottle

dim tusk
dim tusk
distant tulip
tawny jungle
distant tulip
dim tusk
#

Oh yeah...

#

Maximum Amount Per Block
A block cannot have more than 65,536 permutations (equivalent to 4 states with 16 values each). Exceeding this limit will result in a content log error and some states being absent from your block.

Maximum Amount Per World
A world should not have more than 65,536 block permutations registered (not necessarily placed). Exceeding this limit will result in the following content log warning:

World with over 65536 block permutations may degrade performance. Current world has XXXXX permutations.

tawny jungle
#

right

#

i forgot about that bit of documentation

dim tusk
#

That's why I said you can't have 200k

tawny jungle
#

of course, that makes sense

dim tusk
#

Even if the block states is past the limit, you can't apply that state on the block

distant tulip
dim tusk
#

Hmm, that's what I'm saying earlier

dim tusk
dim tusk
distant tulip
dim tusk
# distant tulip ๐Ÿคทโ€โ™‚๏ธ maybe this mean that don't matter either
function isWaterBottle(player) {
    const heldItem = player.getComponent("inventory").container.getItem(player.selectedSlotIndex);
    if (!heldItem || heldItem.typeId !== "minecraft:potion") return false;
    const bottle = new ItemStack("minecraft:potion");

    heldItem.nameTag = undefined;
    heldItem.setLore();
    heldItem.clearDynamicProperties();

    return heldItem.isStackableWith(bottle);
}

system.runInterval(() => {
    for (const player of world.getPlayers()) {
        console.error(isWaterBottle(player));
    }
});```
#

Did I do something wrong? It still returns false even if I'm holding every type of potion

distant tulip
#

log all these
heldItem.typeId
heldItem.isStackableWith(bottle)
bottle.isStackableWith(bottle)
to the console?

bright dove
#

How do you dynamically get the id of a block ?

wary edge
random flint
sterile epoch
#

can I make an itemStack with data?

#

like a speed potion

warm mason
sterile epoch
#

damn looks like I'll have to use /give then

sterile epoch
#

Ah, has to be capitalised. My bad.

marsh berry
#

Can anyone point me to a resource to read up on how node.ja works for a Minecraft addon? How to setup so that none native code can work etz?

slow walrus
#

minecraft doesn't use NodeJS

random flint
marsh berry
granite cape
subtle cove
#

sneak and jump button detection

#

also touch <=> keyboardmouse

chilly fractal
#

I swear, there is only one thing I wanna ask you, how the hell do you have coloring?

#

In the console.warn

subtle cove
#

alien JSON.stringify...

chilly fractal
chilly fractal
subtle cove
distant tulip
# dim tusk It returns false
function isWaterBottle(player) {
    const heldItem = player.getComponent("inventory").container.getItem(player.selectedSlotIndex)
    if(heldItem?.typeId == "minecraft:bottle") return false
    return Boolean(player.runCommand('testfor @s[hasitem={item=potion,location=slot.weapon.mainhand,data=0}]').successCount)
}
tawny jungle
#

can playerInteractWithBlock cancel placement?

chilly fractal
tawny jungle
#

how

#

ah

#

nvm

#

nope

#

actually proceed

#

i still odn't know

distant gulch
#

Has anyone ever noticed that the debugger does not work normally on Linux. What should i do?

#

Has the debugger ever worked on Android apks?

granite badger
# distant gulch Has anyone ever noticed that the debugger does not work normally on Linux. What ...
GitHub

VS Code extension that can debug Minecraft TypeScript and JavaScript, as well as display diagnostic information about running content. - Mojang/minecraft-debugger

distant gulch
#

It's more like APK port with libs

#

The game connects, but the debugger session crashes immediately

distant tulip
#

it is mostly for servers development

slow walrus
sterile epoch
#

what's a good way to implement lots of chat commands without a massive switch case?

distant tulip
slow walrus
#

debugger is for any script dev

#

not mostly for servers

distant tulip
#

he said in Linux

slow walrus
slow walrus
#

wassat gotta do with anything

distant tulip
slow walrus
#

well yeah he probably can't but the debugger isn't made mostly for servers

distant tulip
#

outside of bds and in game development?

slow walrus
#

what?

distant tulip
sterile epoch
slow walrus
distant tulip
slow walrus
#

what are you talking about bro

#

lmao

distant tulip
#

๐Ÿ—ฟ

#

forget about it

remote oyster
# slow walrus what are you talking about bro

He is saying that if you use it, you will be using it in a BDS environment prior to production or release of your pack for Realms, if shared for Realms, because you can't utilize the tool to test, and debug your code if running your pack directly on Realms.

slow walrus
#

I don't think that's what he's saying at all

distant tulip
slow walrus
#

ok well that just doesn't make any sense whatsoever then

#

why are you saying a server?

#

you can develop packs for realms on a normal world yk

steady canopy
#

Hello guys, i have a scripting performance question

past blaze
#

I'm just entering here, and all I can say is that the debugger is for Minecraft itself. It's not server specific

steady canopy
#

i've seen that you were having a conversation about something similar with Yaser.

#

but my case is slightly different since im not loading constants. so

I have a clans system (for factions) and i have a question.

This is the structure of my Clans:

type ClanRole = 'owner' | 'veteran' | 'member'
interface ClanMember {
    role: ClanRole;
    name: string;
    power: number;
    joinDate: number;
    lastActivity: number;
}

export interface Clan {
    displayName?: string;
    id: string;
    shield: number;
    creation: number;
    members: ClanMember[];
    isPublic: boolean;
    owner: string;
    claims?: string[];
    friendlyFire: boolean;
}

The storage im using is Dynamic Properties, saving the stringified objects there.

The data will be constantly edited during the play time, some properties such as displayName, shield, isPublic, friendlyFire, members, could be constantly changing.

So my question is, is it a good practice to cache all the clans when the world starts? (Im 100% sure it won't be more than 100k clans, 100k clans is actually too much for the average players that play on the server where im using this)

Or what's my best option for this case?

slow walrus
#

wow uh

#

I would definitely not

#

which of those fields in the Clan interface are most often accessed?

steady canopy
slow walrus
#

ah I see

steady canopy
#

and claims might be also modified constantly but not much since claims have a price and it's very high.

slow walrus
#

what is shield exactly? Out of all those it seems the most active one

#

I'm assuming a value that can change very quickly?

steady canopy
slow walrus
#

Ah ok

steady canopy
#

SInce shields are expensive too

#

they won't use it too much

slow walrus
#

how often would you say those change?

#

saw you made a post

steady canopy
#

members, conditionally, will change everytime a player joins / leaves, to adjust their power, displayName, isPublic and friendlyFire can be changed at any time by the owner. The shield can change everytime someone buys it in the faction but as i said it's expensive so won't occur very often

#

Yeah so we don't spam here

#

#1316413003838783488 In case you want to help with this issue go to my post please! ๐Ÿ™‚

distant tulip
distant tulip
#

we are talking about using the debugger in Linux, as far as i know the only option is using it with bds sense there is no bedrock for Linux.
unless the un-offecial version can run with the debugger

wary edge
#

Another Linux L. Windows stays superior.

slow walrus
burnt robin
sharp elbow
#

Gigacorp hegemony reigns supreme

tight sparrow
#

Is it possible to reset the cooldown when it hit entity

scarlet sable
tight sparrow
scarlet sable
tight sparrow
#

I mean I want the cooldown will be reset if I hit entity

solar dagger
#

how do i get the face of a block that the player was facing when they broke it?

scarlet sable
#

and player hits of course

dawn zealot
#

how do i make my item name tags always show

#

like when its on the floor it will say the nametag of the item

dim tusk
#

It's nameable component the always_show should be true

dim tusk
dawn zealot
dim tusk
#

-# if I cns find it

dim tusk
dawn zealot
#

heh?

dim tusk
distant tulip
#

nameable component when

dawn zealot
dim tusk
dim tusk
# dawn zealot i mean like when i drop an item i want its name to be displayed above it on the ...

Then you need to overwrite the entity file of the entity entity since you can't access it so make your own...

{
  "format_version": "1.13.0",
  "minecraft:entity": {
    "description": {
      "identifier": "minecraft:item",
      "is_spawnable": false,
      "is_summonable": false,
      "is_experimental": false
    },
    "components": {
      "minecraft:tick_world": {},
      "minecraft:hurt_on_condition": {
        "damage_conditions": [
          {
            "filters": { "test": "in_lava", "subject": "self", "operator": "==", "value": true },
            "cause": "lava",
            "damage_per_tick": 4
          }
        ]
      },
      "minecraft:nameable": {
        "always_show": true,
        "allow_name_tag_renaming": true
      },
      "minecraft:physics": {},
      "minecraft:is_hidden_when_invisible": {},
      "minecraft:pushable": {
        "is_pushable": false,
        "is_pushable_by_piston": true
      }
    }
  }
}```
distant tulip
#

or use particles to display a name

dim tusk
dawn zealot
#

wait nvm i thought of a way

dim tusk
#

Can you detect you're in the village using scripts?

dim tusk
#

Animation controller here I go

dawn zealot
#

how do i get all entities in the overworld again i just remember it being world.getAllEntities()

alpine ibex
#

Does anybody know how I could summon particles and sound by script when being hit for example it triggers?

simple arch
#

How can I change a player/entity skin? I'm trying to do that with simulated players but to no avail.

steady canopy
simple arch
#

I mean I can try and do a sample of it I just don't know the code for it.

steady canopy
#

@simple arch

#

it's as simple as that

simple arch
#

But also I'm kind talking about custom ones too not just any of the skin that the simulated player has. But I can give it a shot ig.

steady canopy
#

Like changing the skin to something that isn't in the entity's resource is not possible in any way

simple arch
steady canopy
#

That's why he has a limit of skins, numbers, he doesn't load any skin he wants from nowhere

#

If you wanna do that

simple arch
#

So I can't exactly do that? Just to be clear

steady canopy
#

What is in the video you can do it

simple arch
#

Yes I want to do that

steady canopy
#

by modifying the zombie's RP

steady canopy
# steady canopy

You create a ModalFormData with a slider that has all the possible mark_variant values or skin_id values and set the entity's component like this to that value .

simple arch
#

So to be sure I have to modify the simulated player resource pack. But nobody has ever done to players correct?

vital halo
#

For some reason the onPlace custom component hook is refusing to pass an argument to my function

#

It's returning undefined

#

bridge makes it look like a javascript error, as the IDE is not even acknowledging the data type that the hook should be passing to the function (but doing it for other components)

steady canopy
#

To do what's in the video here's a function:


import { Entity, Player } from '@minecraft/server'
import { ModalFormData } from '@minecraft/server-ui'

function changeSkin(player: Player, entity: Entity, possibleSkins: number[], component: 'mark_variant' | 'skin_id'){
    new ModalFormData()
    .title('Change Skin')
    .slider('Skin ID', possibleSkins[0], possibleSkins[possibleSkins.length - 1], 1, possibleSkins[0])
    .show(player).then(response => {
        if (response.canceled) return;
        const skinId = response.formValues[0] as number

        entity.getComponent(component).value = skinId
    })
}
#
import { Entity, Player } from '@minecraft/server'
import { ModalFormData } from '@minecraft/server-ui';
function changeSkin(player, entity, possibleSkins, component) {
    new ModalFormData()
        .title('Change Skin')
        .slider('Skin ID', possibleSkins[0], possibleSkins[possibleSkins.length - 1], 1, possibleSkins[0])
        .show(player).then(response => {
        if (response.canceled)
            return;
        const skinId = response.formValues[0];
        entity.getComponent(component).value = skinId;
    });
}

And here's in javascript

#

Usage:

changeSkin(player, entity, [0, 1, 2, 3], 'mark_variant')
#

So the entity's skin is changed by it's mark_variant component and it has 4 possible values (0,1,2,3,4)

steady canopy
#
world.getDynamicPropertyTotalByteCount()

For me returns 6200373 how do i convert that to MBS? what is that number? i don't understand in what digital storage form is that

#

And also, does this affect the performance in any way?

vital halo
#

I have this line of code.

let playerEquipment = (player.getComponent("equippable")).getEquipment(EquipmentSlot.Mainhand);

getComponent is returning an entityComponent, but .getEquipment requires an entityEquippableComponent and is not running. is there some way to fix this issue?

#

I know I can't cast in javascript but what can I do to get the equipment?

alpine ibex
#

Does anybody know how to trigger something when punching?

wary edge
dawn zealot
#

how do i test when my snowball breaks? like hits a block

vital halo
#

they work!!

sterile epoch
#

what's the difference between world.getPlayers() and world.getAllPlayers()?

gaunt salmonBOT
flat barn
flat barn
#

so it looks like yours is

#

6.2mb roughly

remote oyster
# steady canopy And also, does this affect the performance in any way?

Absolutely it impacts performance. You are reading and storing large data to possibly change only a single value. You need to reconsider how you store your data using Dynamic Properties. Remember, Dynamic Properties don't need to be used to design a database that is Monolithic. Due to the uniqueness of how Dynamic Properties work, there are far more efficient ways to make a database, with less complexity.

tight bloom
#

What's the format for using permutation.resolve()? I'm trying to set a permutation on a block while not resetting other permutations, and it seems like this is what I need to do it

#

I haven't been able to see someone using .resolve() for multiple permutations in this server

dim tusk
wary edge
thorn flicker
tight bloom
#

withState... I see

viscid horizon
#

anyone know what i can do to make it so my scripts update live instead of me having to reload the world manually everytime

viscid horizon
wary edge
#

Thats as best you can do.

viscid horizon
#

so i canโ€™t just make something automatically reload my scripts in an interval?

fiery solar
wary edge
#

It'll get quite annoying though imo, having it reload on save each time.

viscid horizon
#

what if i just wanted it running in a world

#

i suppose a command block running the reload command could work

wary edge
#

Command blocks don't have the proper permission level.

viscid horizon
#

couldnโ€™t i also just have something reload the world using runCommand?

fiery solar
karmic pond
#

why does the afterEvents.playerSpawn not detect player switching dimensions?

slow walrus
#

because the player isn't respawning

karmic pond
#

but does it not spawn the player..?

slow walrus
slow walrus
karmic pond
#

ohh I didn't see they added that thank you

#

a lot of new events since I coded last time

meager pulsar
#
world.beforeEvents.chatSend.subscribe(({message,sender,cancel})=>{
    if(message == `mh! getGuide`){
        cancel = true
        system.run(()=>{
            sender.runCommand(`give @s mh:guide`)
        })
    }
```whatยดs the right way to call this event? and what version of minecraft-server do i need to use?
karmic pond
#

latest version is 1.17.0-beta

remote oyster
#

In other words, it will fail to work.

meager pulsar
remote oyster
shut citrus
#

can I use beforeDataDrivenTrigger event?

queen prism
#

system.afterEvents.scriptEventReceive.subscribe((event) => {
    const sourceBlock = event.sourceBlock
    const source = event.sourceEntity
    const target = source.target;
    const message = event.message;
    try {
      switch (event.id) {
        case "toro:set_property":
          SetProperty(source,event.message);
          break;
      }
    } catch {

    }
});
function SetProperty(Source, Details) {
  let detailsSplitter = details.split('/');
  let propertyName = parseInt(detailsSplitter[0]);
  let propertyType = detailsSplitter[1];
  let propertyValue = detailsSplitter[2];
  let propertyMin = detailsSplitter[3];
  let propertyMax = detailsSplitter[4];
  if (propertyType == "float")propertyValue = parseFloat(propertyValue);
  if (propertyType == "int") { 
    
    propertyValue = parseInt(propertyValue);
    propertyMin;
    propertyMax;
    Source.SetProperty(propertyName, Math.min(Math.max((propertyValue),propertyMin),propertyMax));

  }
  if (propertyType == "float") { 
    
    propertyValue = parseFloat(propertyValue);
    parseFloat(propertyMin);
    parseFloat(propertyMax);
    Source.SetProperty(propertyName, Math.min(Math.max((propertyValue),propertyMin),propertyMax));

  }
  if (propertyType == "string") { 

    propertyValue;
    Source.SetProperty(propertyName, propertyValue);
    
  }
}```

Can anyone tell me what's missing in this?
#

The content log kept saying that the system was undefined.

random flint
queen prism
#

Alr thanks.

carmine yarrow
#

Just to be sure, since inputPermissions is read-only, we have to set them via commands?

warm mason
dim tusk
distant tulip
dim tusk
distant tulip
#

ah, yeah

dusky pulsar
#

-# cough cough that's my code cough I fixed it since she sent that version of it

carmine yarrow
#

Since it's not explicitly said in the docs (or I'm blind), we can listen to the response of an HTTP request right?
With
await http.request(req).then((response) => { })

gusty bramble
#
import { ItemStack } from '@minecraft/server';

dimension.spawnItem(new ItemStack('minecraft:stick', 1, location);```

^ how would I make this summon at a set location like 0:0 
-# itโ€™s probably really obvious but Iโ€™m stupid lol
slow walrus
#
import { ItemStack } from '@minecraft/server';

const location = { x: 0, y: 0, z: 0 }
dimension.spawnItem(new ItemStack('minecraft:stick', 1), location);
gusty bramble
#

Wow itโ€™s really that simple Jesus I need to learn more anyway thx

dense sun
#

which is more stable?

player.runCommand
or running the command in the dimension
or tick.json

warm mason
dense sun
#

ight

distant gulch
#

-# but well, its way more complicated

#

However,

can i make a SimulatedPlayer following a targeted Player? when i tried to, it just walked into the endless... .

#

by the way, im not that experiented with the gametest api

random flint
carmine yarrow
#

Is there a way to make an entity invulnerable with ScriptAPI ?
I don't believe so but there are so many smart people here...

distant tulip
pale terrace
#

I get an error saying that the value is outside the range of my property in the player, but this does not happen with entities, only with the player and with all the properties, can someone help me?

distant tulip
pale terrace
# distant tulip share your property and script

Property:

"a:bar": {
          "type": "int",
          "range": [ 0, 21 ],
          "default": 21,
          "client_sync": true
        },```
Script:```js
system.afterEvents.scriptEventReceive.subscribe((data) => {
  data.sourceEntity.setProperty(data.id, data.message)
})```
Command:
```/scriptevent a:bar 9```
distant tulip
pale terrace
#

thank you

distant tulip
#

your welcome

patent tapir
#

Can anyone help me

drifting ravenBOT
patent tapir
#

There

#

Thereโ€™s my question

#

Iโ€™m not writing it all here

distant gulch
#

Anyways, Thanks.

Seems to be my fault because i wasnt looking enough

vital halo
#

Is there a way to give the player a custom component without using player.json?

wary edge
vital halo
wary edge
#

System.runInterval -> getPlayers -> check -> apply effect.

vital halo
#

Okay so there is a function for that, thank you!

distant tulip
#

getPlayers -> get inventory component -> loop through the items -> check tags -> apply effect

burnt robin
#

anyone know why server-net only sends out one request per startup, i start the server the requests sends after that, nothing

#

its just very annoying

empty quail
#

Can the enchantments on an item be modified through scripting? Resolved

empty quail
#

What is this issue with Bridge and how do I resolve it

main.ts

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

^ "Cannot find module '@minecraft/server' or its corresponding type declarations. (2307)"

manifest.json

{
"module_name: "@minecraft/server",
"version": "1.18.0-beta"
}
patent tapir
#

Or the version isnโ€™t good

#

Just add
โ€œentryโ€: โ€œmain.tsโ€
To the manifest module

empty quail
patent tapir
empty quail
patent tapir
#

But apparently you need it for it to work

#

And then you need to make a main.ts in your scripts folder

empty quail
patent tapir
patent tapir
#

Try setting โ€œbeta-apiโ€ in the config to โ€œtrueโ€

#

That would be upcomingcreatorfeatures

#

Sorry

#

I think

ruby haven
#

Can I access structure properties to scripts? structures in Minecraft like villages

dim tusk
#

Uhuh

random flint
distant gulch
#

je, I already thought something like that

astral quarry
#

Is there any hacky ways to get the entity height?

#

Like, entity height as in hey a creeper is roughly 1.5 blocks tall.

knotty plaza
rigid meadow
#

im trying to get today's date by this code but the output is off by 1.
String(date.getDate()).padStart(2, "0")

valid ice
#

It always returns UTC in Minecraft, btw

astral quarry
near siren
#

Is there any way to get the equippable component from an entity or is it just borked? All it returns is undefined

dim tusk
near siren
#

Bedrock wants to get in my way huh ๐Ÿ˜ญ

dim tusk
near siren
#

Oh dang

fallen cape
astral quarry
#

Was driving me nuts all night long lol.

dim tusk
#

Nvm

shut citrus
#

seem like my window system in there

slow walrus
shut citrus
tight plume
#

Guys does setDynamicProperty stack? For example, setting two properties with the same ID. Would this give out errors or ignores it?

warm mason
warm mason
#

#1067876857103536159

burnt remnant
#

my bad muscle memory to come here ๐Ÿ˜‚

warm mason
#

show code

burnt robin
slow walrus
#

you gotta show ur code dude

burnt robin
#
import * as net from "@minecraft/server-net";

const data: any = {
    "table": "test",
    "columns": [
        "name VARCHAR(30)"
    ],
    "time": null
};

const url = `http://localhost:3000/api/v1/sql/create`;

console.log(url);

const req = new net.HttpRequest(url);

req.method = net.HttpRequestMethod.Post;
const sent_time = Date.now();
console.log("Sent Time:", sent_time);
console.log(req.body);

data.time = sent_time;

//@ts-ignore
req.setHeaders([new net.HttpHeader("data", JSON.stringify(data))]);

const httpClient = net.http;

(async () => {
    const res = (await httpClient.request(req));
    console.log(res.body);
    console.log("Recieved Time:", Date.now() - sent_time);
})();
burnt robin
#

i just changed it to test create

slow walrus
#

well your only sending it once

slow walrus
#

which part are you wanting to always send or whatever

#

you want it to happen every tick?

#

what do you want it to do?

quick shoal
#

Idk I just ask

slow walrus
burnt robin
#

its either somethign in the server.properties or mojang being mojang and limiting us again but, it wont send when you reload this is just in the index fike

quick shoal
burnt robin
#

im just storing a few things externally

slow walrus
burnt robin
#

bds console

slow walrus
#

hmm

burnt robin
#

i can screenshare in a vc(no mic, cant hear)

#

its not the highest quality right now

slow walrus
#

can you scroll up the bds console a lil

burnt robin
#

could u see what i was showing?

slow walrus
#

there's something about server properties

slow walrus
#

ah nvm that's something else

#

that's pretty weird

#

might be a bug idk

burnt robin
#

exactly

#

but there is a possible issue

slow walrus
#

can you restart the node app and then try /reload in the bds?

burnt robin
#

take a look here

#

its almost as if theres just nothing canceling the last packet

#

yeah here 1 sec

#

its server sided

#

not the node app

slow walrus
#

yeah

#

try chucking a system.run around the req part

#

see if that does anything

#

damn that is strange

burnt robin
#

ok i think i know the issue

#

sooo look at my 3000 port connections

slow walrus
#

oh wait yeah

#

the connection might still be open or something

burnt robin
#

it has 3 things that mention 3000, 2 are established, so the network request isnt completed so i think its just not reciving it, do i do net.http.cancelAll after i recieve a response?

#

2nd one is after stoping the server

default:~/dev/server$ sudo lsof -i:3000
COMMAND    PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
node      5531 root   21u  IPv6 482034      0t0  TCP *:3000 (LISTEN)
node      5531 root   22u  IPv6 483338      0t0  TCP localhost:3000->localhost:36118 (ESTABLISHED)
bedrock_s 5554 root   13u  IPv6 484354      0t0  TCP localhost:36118->localhost:3000 (ESTABLISHED)
default:~/dev/server$ sudo lsof -i:3000
COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
node    5531 root   21u  IPv6 482034      0t0  TCP *:3000 (LISTEN)
slow walrus
#

you sure your http request is set up right?

#

honestly don't know sorry dude

#

I assume it's a bug

burnt robin
#

my bad, my pc crashed

burnt robin
wheat condor
#

player.dimension.fillBlocks({ from: volumeA.get(player), to: volumeB.get(player) }, text[2])
is this the right way to use BlockVolumeBase?

#

volumeA,b are vec3

distant tulip
north depot
#

what does a "return null" Do?

#

its like a cancel event?

wheat condor
north depot
#

ohhh... thanks....

grim raft
#

yo

#

why does setScore not work in scoreboardPlayerMaxHealth

const scoreboardPlayerHealth = world.scoreboard.getObjective("health")
const scoreboardPlayerMaxHealth = world.scoreboard.getObjective("maxhealth")

system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        const playerHealthComp = player.getComponent(EntityHealthComponent.componentId);

        if (!playerHealthComp) return;

        const currentHealth = playerHealthComp.currentValue;
        const maxHealth = playerHealthComp.maxValue;

        scoreboardPlayerHealth.setScore(player, currentHealth);
        scoreboardPlayerMaxHealth.setScore(player, maxHealth)
    }
}, 1);```
warm mason
#

playerHealthComp.maxValue -> playerHealthComp.effectiveMax

normal aurora
#

Looking for public Bedrock servers, anyone have recommendations?

warm mason
#

or just go to #off-topic

coral ermine
#

How to check player health?

          if (health.current <= 0)```
is this right?
warm mason
#

health.currentValue

sage sparrow
#

hi there, is there a easier way to get entities from ray but creating some kind of area?
for instance instend getting entities fron a straight line on ray, get entities from from a area like a cone? so as farther more blocks to get entities will be included?

warm mason
sage sparrow
#

I think yes, I want to causa damage to entities inside this cone, so getting straight line will only get part of them, farther entities that is slightly located to both sides from my line of view will not be included

warm mason
# sage sparrow I think yes, I want to causa damage to entities inside this cone, so getting str...
function getEntitiesFromLargeRay(dimension, fromLocation, direction, rayLength = 64, options = {}) {
  let entities = []
  options.maxDistance = options.maxDistance || 1
  for (let i = 0; i < rayLength; i++) {
    options.location = {
      x: fromLocation.x + direction.x*i,
      y: fromLocation.y + direction.y*i,
      z: fromLocation.z + direction.z*i
    }
    entities = entities.concat(dimension.getEntities(options))
  }
  return entities
}

Usage example:

let entities = getEntitiesFromLargeRay(word.getDimension("overworld"), {x:0, y: 0, z: 0 }, {x: 0.5, y: 0, z: 0.5}, 10, {maxDistance: 5})
#
  • dimension - player.dimension
  • fromLocation - player.location
  • direction - player.getViewDirection()
  • rayLength - The name speaks for itself
  • options - EntityQueryOptions
sage sparrow
#

great starting point, I will work on that, thank you

steady canopy
dim tusk
#

Use tickingarea ๐Ÿคท

warm mason
winter plaza
#
import { world } from "@minecraft/server";

world.afterEvents.itemUse.subscribe(({ source, itemStack }) => {
  const equipment = source.getComponent("equippable");
  if (itemStack.typeId == "dlvn:pokeball_pokemon" && itemStack.getLore().includes("Pikachu Level 5")) {
   source.runCommandAsync(`say foi? ` + itemStack.getLore().replace("Pikachu Level ", ""));
  }
});
#

why doesn't "replace" work?

cold grove
#

doesnt getLore() returns an array??

#

oh yes, it does

remote oyster
#

Yea, it returns a string[].

winter plaza
remote oyster
# winter plaza So what do I do?

Have to sort through each string in the array until you find the specific string you are looking for, then replace and apply to your message.

winter plaza
#
import { world } from "@minecraft/server";

world.afterEvents.itemUse.subscribe(({ source, itemStack }) => {
  const
    equipment = source.getComponent("equippable"),
    test = itemStack.getLore();
  if (itemStack.typeId == "dlvn:pokeball_pokemon" && itemStack.getLore().includes("Pikachu Level 5")) {
   source.runCommandAsync(`say foi? ` + test.replace("Pikachu Level ", ""));
  }
});
#

I tried like this, but it didn't work

cold grove
winter plaza
#

How do you use a filter?

remote oyster
winter plaza
#

How, thanks

#

but I wanted it to be from the lore itself, because when I use the same item, but with the description like "Charmander Level 5", I will have to create another filter

remote oyster
# winter plaza but I wanted it to be from the lore itself, because when I use the same item, bu...
// Define a lookup object for lore patterns and their handlers
const loreHandlers = {
  "Pikachu Level": (lore) => {
    const level = lore.replace("Pikachu Level ", "");
    source.runCommandAsync(`say Pikachu is at Level ${level}`);
  },
  "Charmander Level": (lore) => {
    const level = lore.replace("Charmander Level ", "");
    source.runCommandAsync(`say Charmander is at Level ${level}`);
  },
  // Add more handlers as needed
};

if (itemStack.typeId === "dlvn:pokeball_pokemon") {
  const lore = itemStack.getLore();

  for (const line of lore) {
    // Check each lore line against the handlers
    for (const key in loreHandlers) {
      if (line.startsWith(key)) {
        loreHandlers[key](line); // Call the handler dynamically
        break; // Stop checking further handlers for this line
      }
    }
  }
}
#

That is about as good as you are gonna get in terms of efficiency. Based on your concept.

winter plaza
#

Ok

#

thank you very much

#

you are the best!

patent tapir
#

How do I test if a player has al 4 pieces of netherite armor in their inventory

patent tapir
#

I donโ€™t know how to do that

#
import { world, system, Dimension, EntityInventoryComponent, } from "@minecraft/server"
const ascensionArea = {
  x = 9999,
  y = 99,
  z = 9999
}
const lookAt = {
  x = 10003,
  y = 100,
  z = 9999
}
world.beforeEvents.chatSend.subscribe(data => {
  const sender = data.sender
  const message = data.message

  const senderInventory = data.sender.getComponent(EntityInventoryComponent)
  world.getDimension("overworld").getPlayers()
  if (message.startsWith("!") && message.substring(1).toString().toLowerCase() == "ascend") {
    if (world.scoreboard.getObjective("coins").getScore(sender.scoreboardIdentity) >= 100000 && world.scoreboard.getObjective("kills").getScore(sender.scoreboardIdentity) >= 25) {
      sender.teleport(ascensionArea, { facingLocation = lookAt })
    }
  }
})```
#

I want the command to run only when they have all 4 pieces of netherite armor in their inventory as well as 100k coins and 25 kills

distant tulip
patent tapir
#

Oh, what?

#

What do you mean by that

#

Inventory?

#

I donโ€™t care if theyโ€™re wearing it i just want them to have them

#

Also am I using vector3 correctly

distant tulip
#

you want to test if the armor is in the armor slots or inventory in general

distant tulip
#
  const inventoryComponent = player.getComponent("inventory");
  const inventory = inventoryComponent.container;
  const netheriteArmor = [
    "minecraft:netherite_helmet",
    "minecraft:netherite_chestplate",
    "minecraft:netherite_leggings",
    "minecraft:netherite_boots",
  ];

  // Keep track of armor pieces found
  let foundArmor = 0;

  for (let slot = 0; slot < inventory.size; slot++) {
    const item = inventory.getItem(slot);
    if (item && netheriteArmor.includes(item.typeId)) {
      foundArmor++;
    }
  }

  if (foundArmor === 4) {
    //...
  }
patent tapir
#

Am i using vector3 correctly btw

#

By making an object with x, y, and z

#

And using that as the vector

distant tulip
#

yes

patent tapir
#

Ok great

winter plaza
#
hurt.typeId.split("dlvn:")[1].toUpperCase()

When I use "toUpperCase" it capitalizes the entire word, I only want the first word.

steady canopy
late cliff
vestal spruce
dim tusk
#

Lmao i just realized someone already did it

late cliff
#

can properties, components (specially mark_variant), and tags not be accessed from a projectile that has hit an entity as ive tried this and I either get an error or undefined?

world.afterEvents.projectileHitEntity.subscribe((data) => {
  const {dimension, hitVector, location, projectile, source} = data
  if(projectile.typeId == 'cc:blaster_proj'){
    const lev = projectile.getProperty('cc:level')
    const level = projectile.getComponent('minecraft:mark_variant').value
    const levels = projectile.getTags()
    world.sendMessage(`${lev} | ${level} | ${levels}`)
  }
})
dim tusk
#

you could use the projectilehitentity if you don't have that but if you do just resort using the entity remove

quick shoal
#

What can simulated player do

simple arch
#

e.g, breaking a block

late cliff
dim tusk
patent tapir
#

Why is Minecraft throwing an error at the line of code with the x variable on it const buttonLocation = { x = 10003, y = 101, z = 9999 }

#
]```
#

It invalidated my ENTIRE main.js

#

But it didnโ€™t throw any errors for the other files that had the exact same kind of object

#

Iโ€™m using it as a vector3

#

And my file has all of itโ€™s brackets matching up so it should be fine

dim tusk
patent tapir
dim tusk
#

can't help you if you just give me thaat object

patent tapir
# dim tusk can you share the whole snippet atleasst?
world.afterEvents.buttonPush.subscribe((data) => {
    const buttonLocation = {
        x = 10003,
        y = 101,
        z = 9999
    }
    const spawn = {
        x = 0,
        y = 64,
        z = 0
    }
    const button = data.block.location
    if (button.x === buttonLocation.x && button.y === buttonLocation.y && button.z === buttonLocation.z) {
        //if (button === buttonLocation) {
        world.sendMessage({
            rawtext: [
                {
                    text:
                        `ยง5${data.source} HAS ASCENDED`
                }
            ]
        })
        world.getDimension("overworld").playSound("mob.enderdragon.growl")
        world.getDimension("the_end").playSound("mob.enderdragon.growl")
        data.source.teleport(spawn)
    }
})```
#

I dunno how much I should send so I sent the whole darn thing

dim tusk
patent tapir
#

I think Iโ€™m gonna remove the playsound tho cuz I can do that with a command block

#

Canโ€™t omit the tellraw because of source name

dim tusk
patent tapir
dim tusk
#

yeah i forgot wait

dim tusk
patent tapir
#

What did i do

dim tusk
#

it only have source

patent tapir
#

Wdym

dim tusk
#

data.block.location is not valid

patent tapir
#

Bruhโ€ฆ

dim tusk
#

i chcked the preview and not preview and only the source exist

#

also

patent tapir
#

Then how am I supposed to get the name of the person through a /tellraw nesting in /execute

dim tusk
#

that's not how you use object

patent tapir
#

โ€ฆโ€ฆ..

dim tusk
dim tusk
#

you used colon not equals

patent tapir
#

Well Iโ€™m gonna get some ice cream brb

dim tusk
#

i just noticed it mybad

patent tapir
#

Please tell me how to get username of player through /execute /tellraw

dim tusk
#

that docs doesn't include it that's why i assumed

#

and also you can get the name using source.name

dim tusk
# patent tapir Well Iโ€™m gonna get some ice cream brb
world.afterEvents.buttonPush.subscribe(({ source, block }) => {
  const spawn = { x: 0, y: 0, z: 0 };
  const buttonLoc = { x: 0, y: 0, z: 0 };

  if (block.location.x === buttonLoc.x && block.location.y === buttonLoc.y && block.location.z === buttonLoc.z) {
    world.sendMessage(`${source.name} ascended!`);
    source.teleport(spawn);
  }
});```
dawn zealot
#

can someone help rq

dim tusk
dawn zealot
#

basically im (this is just an example ik its not correct) im trying to get the name from player 1 that matches the ID of 1, and display it as a button name

#

wait i might know

#

nvm im dumb

late cliff
dawn zealot
patent tapir
#

Hey so I finally got my scripts to work but uhhhhhhhhhhhh

#

[Scripting][error]-ReferenceError: Native function [ScreenDisplay::setTitle] does not have required privileges. at <anonymous> (goToAscend.js:47)

#

So how do I elevate the script permissions?

dim tusk
#

Wrap the part of the code with system run

patent tapir
#

Ok so system.run bypasses this?

#

Is there a way for me to naturally set the script permissions higher?

#

Like for example wtf is permissions.json

patent tapir
dim tusk
slow walrus
# patent tapir Like for example wtf is permissions.json

that's not what it means. In beforeEvents, they run before the game tick (as implied by the name) in a read-only state, so that means you can't call functions that modify the world or anything inside it. You can check which functions don't have "permissions" by checking the function description, where it'll say something like "this function can't be called in read-only mode". By using a system.run, you delay that code till the next game tick, where the state is read & write, so it has the proper "permissions"

slow walrus
patent tapir
#

Does that also delay the rest of the code though, including the event.cancel

slow walrus
#

only the stuff that can't run in a readonly state

#

event.cancel can't be delayed otherwise it does nothing

patent tapir
#

Yeayeayea but if event.cancel is at the end of the world.beforeEvents.chatSend function will system.run delay it until message has already been sent

slow walrus
#

no, only the stuff inside of the callback is delayed

patent tapir
#

Thanks for the help

slow walrus
#

no problem

patent tapir
#

Also

#

Does system.run need the () => {}

#

In the parentheses

#

Or can i just directly put the sender function into the system.run

dim tusk
patent tapir
#

Even if the nested parentheses are empty

dim tusk
patent tapir
#

Why isnโ€™t data.cancel = true working

#

I even put it at the start of the world.beforeEvents function and it doesnโ€™t stop my message from being sent

dim tusk
patent tapir
#
import { world, system } from "@minecraft/server"
const ascensionArea = {
  x: 9999.5,
  y: 99,
  z: 9999.5
}
const lookAt = {
  x: 10003.5,
  y: 99.5,
  z: 9999.5
}

world.beforeEvents.chatSend.subscribe(data => {
  data.cancel = true
  const inventoryComponent = data.sender.getComponent("inventory");
  const inventory = inventoryComponent.container;
  const netheriteArmor = [
    "minecraft:netherite_helmet",
    "minecraft:netherite_chestplate",
    "minecraft:netherite_leggings",
    "minecraft:netherite_boots",
  ];
  let foundArmor = 0;

  for (let slot = 0; slot < inventory.size; slot++) {
    const item = inventory.getItem(slot);
    if (item && netheriteArmor.includes(item.typeId)) {
      foundArmor++;
    }
  }
  const sender = data.sender
  const message = data.message

  world.getDimension("overworld").getPlayers()
  if (message.startsWith("!") && message.substring(1).toString().toLowerCase() == "ascend") {
    if (world.scoreboard.getObjective("coins").getScore(sender.scoreboardIdentity) >= 100000 && world.scoreboard.getObjective("kills").getScore(sender.scoreboardIdentity) >= 25 && foundArmor === 4) {
      system.run(() => {
        sender.teleport(ascensionArea, { facingLocation: lookAt })
      })
    } else {
      system.run(() => {
        sender.onScreenDisplay.setTitle({
          rawtext: [
            {
              text:
                "You can't\nascend yet"
            }
          ]
        })
      })
    }
  }
})```
#

Itโ€™s a lot

#

Two things I want to fix from this too though

#
  1. How do I close the playerโ€™s chat immediately upon sending the command
  2. I want to check for at least 1 of every netherite armor piece is in their inventory
neat hound
#

Why oh Why... If I cancel the playerInteractWithBlock Event, where the space that I touched from is air, so can take the block normally, why do I see a quick blip of it, then it disappears... is it me, or has anyone else noticed this? Is this why it is still beta?

#

So this really looks bad when I place those pink slabs connecting them, because it shows the default placement then switches to the new permutation placement

#

Does not matter too much between if I let the interact or the placeblock event handle it... only one that does not do that is the block's BP file...

wary edge
#

You should use beforePlayerPlaceBlock and see if it still occurs.

#

According to the afterevents ordering anyways, I presume beforevents have the same ordering.

neat hound
# wary edge Probably because place block triggers before interact.

According to my testing where I actually show that stuff on the screen. The the player interact with block, the before event, happens before the player place block, before event. And on top of that, which kind of makes sense, if you cancel the interact event, it will not do the place event. So you're saying that the documentation says it should be the other way?

#

That was voice to text so if anything is off blame Google because I do not talk. Funny

slow walrus
#

cause the client predicts that the block will be placed, so it renders it, but then the server cancels the event, so it gets "un" rendered

neat hound
#

Yeah, well that sucks

tight plume
#

Anyone quick question, how do i get the item in the armor slots of the player

#

i forgot what method that was

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

const ascendPos = { x: 9999.5, y: 99, z: 9999.5 };
const lookAtPos = { x: 10003.5, y: 99.5, z: 9999.5 };

const netheriteArmor = [
  "minecraft:netherite_helmet",
  "minecraft:netherite_chestplate",
  "minecraft:netherite_leggings",
  "minecraft:netherite_boots",
];

function hasFullArmor(player, armor = []) {
  const equip = player.getComponent('equippable');
  const head = equip.getEquipment('Head');
  const chest = equip.getEquipment('Chest');
  const legs = equip.getEquipment('Legs');
  const feet = equip.getEquipment('Feet');
  
  return [head, chest, legs, feet].every(item => item && armor.includes(item.typeId));
}

function getScore(player, objName) {
  const obj = world.scoreboard.getObjective(objName);
  return obj ? obj.getScore(player) || 0 : 0;
}

world.beforeEvents.chatSend.subscribe((data) => {
  const player = data.sender;
  const msg = data.message.trim();

  if (msg.toLowerCase() === "!ascend") {
    data.cancel = true;

    const hasArmor = hasFullArmor(player, netheriteArmor);
    const coins = getScore(player, "coins");
    const kills = getScore(player, "kills");

    if (coins >= 100000 && kills >= 25 && hasArmor) {
      system.run(() => {
        player.teleport(ascendPos, { facingLocation: lookAtPos });
      });
    } else {
      system.run(() => {
        player.onScreenDisplay.setTitle({
          rawtext: [{ text: "You can't\nascend yet" }],
        });
      });
    }
  }
});
patent tapir
#

But thanks

dim tusk
patent tapir
#

Aw

#

Ok

dim tusk
#

Didn't test it so don't expect it would work immediately ๐Ÿ˜ญ

patent tapir
#

Also you forgot to add the netherite armor array to this line which is why it grayed for me

#

const hasArmor = hasFullArmor(player, netheriteArmor);

dim tusk
patent tapir
dim tusk
#

It would work still

#

What software are you using

patent tapir
#

Thatโ€™s what it looked like when I put it in

dim tusk
patent tapir
#

So I added the array

dim tusk
#

I modified it lmao

patent tapir
#

Oh

dim tusk
#

I keep editing the message and you copied the first version lmao mybad

patent tapir
#

Also the dude who sent me the first script to check for if the armor was in the inventory at all it worked fine but I could just have 4 netherite boots and it passed

#

Canโ€™t it just check the entire inventory?

dim tusk
#

Oof

#

Sorry bout that

patent tapir
#

But that wasnโ€™t really true

dim tusk
patent tapir
#

I read it as โ€œyou canโ€™t detect inventory, only armor slotsโ€

dim tusk
# patent tapir But that wasnโ€™t really true
function hasFullArmor(player, armor = []) {
  const inventory = player.getComponent("inventory").container;
  let armorCount = 0;

  for (let i = 0; i < inventory.size; i++) {
    const item = inventory.getItem(i);
    if (item && armor.includes(item.typeId)) {
      armorCount++;
    }
  }

  return armorCount === armor.length;
}```
#

Yeah I just retain your old one :)

patent tapir
patent tapir
#

But i could probably just add an [i] somewhere

patent tapir
#

Trust me, i would know, i have done STRENUOUS testing for the last like 4 hours

#

Before that, I had dinner, and before THAT, more testing!

#

Iโ€™m so glad itโ€™s Saturday tomorrow

#

Pretty much today my iPad was suffering from all the extremely stressing testing where I had 3 applications open at once and usually like 20 players on my world at the same time all day

#

But at some point I have to set the world to invite only because of world breaking exploits from the main.js getting invalidated

#

Am I just a nuisance here?

#

Am I asking for too much?

#

Should I leave?

#

I like the help ;-;

dim tusk
#

And I've been doing this for a long time and don't expect I don't know any solution

patent tapir
#

Ok well I finished my entire laundry while waiting and watching yt

sterile epoch
#

I made a function that takes a date and returns the date as "8d, 3h, 2m"
But if I do long dates, like a year, it'll say "-1y" and idk why

#

does anyone know why this happens

dim tusk
# patent tapir Ok well I finished my entire laundry while waiting and watching yt
function hasFullArmor(player, armor) {
    const inventory = player.getComponent('inventory').container;
    const foundArmor = new Set();
    for (let i = 0; i < inventory.size; i++) {
        const item = inventory.getItem(i);
        if (item && armor.includes(item.typeId)) {
            foundArmor.add(item.typeId);
        }
    }

    return armor.every(piece => foundArmor.has(piece));
}

world.beforeEvents.chatSend.subscribe(ev => {
    if (ev.message === '!test') {
        ev.cancel = true;
        const netheriteArmor = [
            'minecraft:netherite_helmet',
            'minecraft:netherite_chestplate',
            'minecraft:netherite_leggings',
            'minecraft:netherite_boots'
        ];
        if (hasFullArmor(ev.sender, netheriteArmor)) {
            ev.sender.sendMessage('Full set of netherite armor');
        } else {
            ev.sender.sendMessage('Not full set of netherite armor');
        }
    }
});```
#

done

dim tusk
#

do you use the ticks or the date.now?

#

or whatever you used

patent tapir
dim tusk
#

nothing is impossible to me blud..
-# unless I'm really that stupid that idk any way lmao

patent tapir
#

The more I get solutions from u guys the more I have issues with my own requests

#

I have no idea how I was supposed to phrase that

sterile epoch
# dim tusk send the code
export function getTimeRemainingString(endDate) {
    if (endDate === null) return "Permanent";

    const now = new Date();
    endDate = new Date(endDate);
    let years = endDate.getFullYear() - now.getFullYear();
    let months = endDate.getMonth() - now.getMonth();
    let days = endDate.getDate() - now.getDate();
    let hours = endDate.getHours() - now.getHours();
    let minutes = endDate.getMinutes() - now.getMinutes();
    if (minutes < 0) {
        minutes += 60;
        hours -= 1;
    }
    if (hours < 0) {
        hours += 24;
        days -= 1;
    }
    if (days < 0) {
        const prevMonth = new Date(endDate.getFullYear(), endDate.getMonth(), 0);
        days += prevMonth.getDate();
        months -= 1;
    }
    if (months < 0) {
        months += 12;
        years -= 1;
    }
    const timeComponents = [
        years ? `${years}y` : "",
        months ? `${months}mo` : "",
        days ? `${days}d` : "",
        hours ? `${hours}h` : "",
        minutes ? `${minutes}m` : ""
    ].filter(Boolean);

    return timeComponents.join(", ") || "Mute expired";
}
sterile epoch
dim tusk
sterile epoch
#

format of what?

#

i use it whenever i want to show the duration of a ban/mute

dim tusk
#

nvm i get it now..
-# i think?

sterile epoch
#

but in a readable format

dim tusk
#

i want to recreate or test it

sterile epoch
#

sure one sec

wheat condor
#

can someone explain me why this is wrong

#

why is it not registering the component

open urchin
#

custom components are registered in regular script files in the BP/scripts folder

gusty bramble
#

Is there a way to cancel all momentum for the item thatโ€™s summoned with this?

import { ItemStack } from '@minecraft/server';

const location = { x: 0, y: 0, z: 0 }
dimension.spawnItem(new ItemStack('minecraft:stick', 1), location);

I considered just tping the item to the location to do it but I thought there may be a better way

open urchin
gusty bramble
#

Iโ€™ll try

#

Unfortunately it doesnโ€™t seem to effect it

neat hazel
#

How to detect if the player used the item and when I stopped using it
When you use it, you get a tag, when you stop, you lose the tag.

chilly fractal
neat hazel
chilly fractal
#

You're welcome

chilly fractal
neat hazel
# chilly fractal world.afterEvents.itemUseStart

Why is it not working?

mc.world.afterEvents.itemStartUse.subscribe((eventData) => {
  const player = eventData.source;
  const item = eventData.itemStack;

  player.sendMessage("Start")
});
mc.world.afterEvents.itemStopUse.subscribe((eventData) => {
  const player = eventData.source;
  const item = eventData.itemStack;

  player.sendMessage("Stop")
});
chilly fractal
#

ReleaseUse

coral ermine
#

Why event is not working?


world.beforeEvents.playerPlaceBlock.subscribe(event => {
  const player = event.player;
  const block = event.block;
    if (block.typeId === "minecraft:dirt") {
        summoned(player);
        event.cancel = true;
    }
});
chilly fractal
chilly fractal
neat hazel
chilly fractal
neat hazel
chilly fractal
#

Well show me the code you used anyway

neat hazel
# chilly fractal Well show me the code you used anyway
mc.world.afterEvents.itemStartUse.subscribe((eventData) => {
  const player = eventData.source;
  const item = eventData.itemStack;

  player.sendMessage("Start")
});
mc.world.afterEvents.itemReleaseUse.subscribe((eventData) => {
  const player = eventData.source;
  const item = eventData.itemStack;
  
  player.sendMessage("Stop")
});
chilly fractal
#

Well do you do the import like the following:
import * as mc from "@minecraft/server";?

#

If not then that's the error

#

It should work otherwise

neat hazel
neat hazel
winter plaza
#
entityWest = block.dimension.getEntities({maxDistance:6,location:{x:x - 27, y:y, z:z + 3},type:"minecraft:player"},tags:("start_mission");

How do I put a tag filter and scoreboard in this const?

sharp elbow
#

For tags, add the 'tags' array to the object passed into getEntities.

#

To filter by scoreboard, we need to filter the array elements, removing entities who do not match the condition.

winter plaza
#
if (getScore("missions", entityWest) == 3) {}
#

like this?

sharp elbow
#
entityWest = block.dimension.getEntities({
  maxDistance: 6,
  location: {x: x-27, y: y, z: z + 3},
  type: "minecraft:player",
  tags: ["start_mission"]
}).filter(function filterByScore(entity) {
  return getScore("missions", entity) == 3;
});
winter plaza
#

Thanks