#Script API General

1 messages · Page 115 of 1

jolly citrus
#

what

amber granite
#

Are u sure u can't overload commands ?

#

Using the new custom command class ?

jolly citrus
#

how would that help

#

/reload isn't a custom command

amber granite
#

No i mean overload it

#

Make a custom command with the same name

jolly citrus
#

override ?

#

you can't override existing commands

amber granite
#

Sure ?

warped blaze
#

you have to use a namespace and it will be mandatory when typing your custom command in case there's already one with that name in vanilla

prisma shard
#

worldLoad event fires each time you do reload. There is no other possible way to detect as I know that you're trying to detect it as a beforeEvent like fire before everything else are reload, but worldLoad is the most possible way.
system.beforeEvents.tartup event actually fires before EVERYTHING and only fires at entering world. But it doesn't run at reload. So your best bet is probably worldLoad.

#

Also uhhhh

#

Apperantly
player.runCommand("/reload") doesn't work ....

#

Wait I'll try without the slash hmm

distant tulip
#

"worldLoad event fires each time you do reload"
are you sure?

prisma shard
#

No?

#

shit I need to test again

distant tulip
#

i highly doubt it tbh, it is worldLoad and /reload doesn't reload the world
only /reload all will trigger that

prisma shard
distant tulip
prisma shard
distant tulip
#

welp

prisma shard
#

everyday we learn smth new :p

distant tulip
#

i guess so

#

thanks

warped blaze
#

yo is there a way to get the items on shelves?

jolly citrus
#

there's still no way to detect potion type, correct

jolly citrus
#

wait actually i think there is now

hazy kraken
#

anyone know how to fix this errors?

round bone
#

#1067869288859447416

jade grail
#

can anyone give me a good projectile script?

jade grail
lethal bramble
#

read the docs

jade grail
#

theres no way to set an effect on a potion tho right?

#

its only read only

fair quarry
lethal bramble
hazy kraken
lethal bramble
hazy kraken
jade grail
#

huh how do i define an entity in script api?

#

nvm im js dumb

#

so do u always have to spawn an entity in before u can use the shoot function?

frozen vine
#

Is it possible to make a notification using server-ui where it will appear and then disappear again?

thorn flicker
#

you can use scripts to trigger titles and then edit these titles in json ui to make them look how you want though.

#

unless you want a notification that stops players, you can use a form I guess, but that would be annoying.

subtle cove
#

form.show and closeAllForms but it'd be buggy

shy leaf
# jade grail so do u always have to spawn an entity in before u can use the shoot function?

lemme explain how it works:

to shoot a projectile with scripting api, first you need to spawn an entity with projectile component
then, get the projectile component and set the owner so that it doesnt hit the owner upon spawning
lastly, you use shoot function to apply velocity of it. the difference between applyImpulse and shoot function is that the latter allows you to give projectiles uncertainty, and its a lot more consistent than the former

shoot function does not spawn entities. it basically launches the entity, so it will never work without an entity to begin with

subtle cove
#

#1067535608660107284 message

shy leaf
#

lol

#

btw

subtle cove
#

ye, thx swell. it's actually interesting how i copied the link before I've seen ur reply bao_panda_munching

shy leaf
#

werent you green named before?

#

or am i going crazy

subtle cove
#

i left then rejoined

shy leaf
#

yeah i noticed, what happened?

subtle cove
#

uhhh, cant sare much but i need the changes to reduce online stuff

shy leaf
#

i see

drowsy scaffold
#

Is there a way to directly check if the player is in lava? Like I know there's no isInLava, but is there like components or something that I can use instead to check?

shy leaf
drowsy scaffold
shy leaf
drowsy scaffold
shy leaf
#

ow

drowsy scaffold
#

right?

#

it sucks because you can stand in like the corner of lava and then using a single getBlock doesn't return the typeId correctly

frozen vine
lethal bramble
#

how would i force update a block?

#

like, for some reason a block (like a redstone component) is not properly reflecting its intended state

prisma shard
lethal bramble
lethal bramble
gaunt salmonBOT
jolly citrus
#

How do I fix 😢😢

[ERROR] Could not resolve "@minecraft/server-net"

    scripts/eventListeners.ts:12:48:
      12 │ import { beforeEvents as netBeforeEvents } from "@minecraft/server-net";
         ╵                                                 ~~~~~~~~~~~~~~~~~~~~~~~

  You can mark the path "@minecraft/server-net" as external to exclude it from the bundle, which
  will remove this error and leave the unresolved path in the bundle.

[14.08.37] x Error detected while running 'bundle'
#

nvm i think i know what the issue is

#

nvm i dont

#

nevermind i did but

#

now i get this in console

#

yes im running it on bds

distant tulip
buoyant canopy
#

can we check if the entity has died in an entityHurtAfterEvent?

#

without math please

#

actually never mind, i realized i don't need the amount of damage dealt anyway, so i could use entityDieAfterEvent

onyx locust
#

if not, add it

#

also check permissions.json on your bedrock dedicated server files if it includes @minecraft/server-net

#

go to your main server files and navigateconfig > default > permissions.json

jolly citrus
#

thx

jolly citrus
#

but thanks for taking the time anyway

#

how do i apply these options

#

liek where are they used

#

im using PacketSendBeforeEvent

#

but i only want specific packets to trigger/not triggerf it

#

nvm got it now

buoyant canopy
#

I have no idea what happened, i was scripting and when i added a new js file and reloaded the game, i kept getting errors that my custom blocks aren't registered but used in blocks.json, and all of my custom items have disappeared, i thought i missed up something but after thoroughly checking everything i can possibly have done wrong i found nothing, It turns out that all of my addons decided to unequip themselves from my world WHY DID THAT HAPPEN?

pale terrace
#

Hello! any idea of how can I spawn entities in a structure without a custom block?

Jigsaw are not stable

#

idk what to do xD

pale terrace
#

but the update may not be soon

#

1.21.110 just come out

wary edge
#

.120 is likely in 2 weeks. We just entered .130

pale terrace
#

:O

#

thank you

boreal siren
#

Guys, how do I write custom commands in JS?

#

I tried writing it myself, but it only displays a warning that there is no result from the function that it was executed.

granite badger
jolly citrus
#

is there a way to get player ping on server-net

jolly citrus
fallow rivet
#

I want my camera to see an entity as a third person, how can I do this?

rigid torrent
#

How can I check when a player blocks an attack with a shield?

#

Discord search came in clutch

shy leaf
#

(tho you already figured it out sooo)

shy leaf
#

sean

#

no dont

#

dont say it

safe stream
#

is getLightLevel() not released out of beta yet?

lethal bramble
safe stream
#

vsc was throwing an error earlier

#

maybe it's just outdated

lethal bramble
#

vsc isnt really reliable for me, i dont know about you, but i always forget to do npm install whenever i update to a new version

lilac glacier
#

im trying to make my entity have an option to either strafe forward when the target is far and strafe backwards when the target gets closer using scripts but this happens. can anyone lend me a hand?

copper quartz
#

So, I found this admin menu, I'm wanting to try to figure out how to make one myself, but cannot understand the code, is there a way to convert it into a more readable format or do I just have to free ball it?

hazy kraken
shy leaf
jade grail
shy leaf
#

and even then, its limited on info

#

and you basically have to feed the entirety of API documents for it to actually understand

copper quartz
#

ChatGPT barely works

shy leaf
#

it helps with javascript stuff

#

but not scripting api

copper quartz
#

But I'm newer to scripting, so I'm lost out if my mind

#

I js need a site with the functions😭

copper quartz
#

Tysm

#

Would it be easier to make a dialogue form?

subtle cove
#

i'd say gud luck bao_panda_munching

#

once u got the hang of linking forms then u can call it easy

granite badger
#

openai models are dumb

#

ok other ai models can't detect this exists. the addon devs keep their job

prisma shard
#

the addon devs keep their job
not for so long

subtle cove
#

its quite too much for the ai to browse all those objects imo
sending the typings would be more accurate for em

midnight ridge
#
system.runInterval(() => {
  for (const player of world.getAllPlayers()) {
    const inv = player.getComponent("inventory").container;
    const equip = player.getComponent("equippable");

    // --- Get items ---
    const mainHand = inv.getItem(player.selectedSlotIndex);
    const offHand = equip.getEquipment("Offhand");

    // --- Check for magnet ---
    const isMainMagnet = mainHand?.typeId === "minecraft:stick";
    const isOffMagnet = offHand?.typeId === "minecraft:stick";
    const holdingMagnet = isMainMagnet || isOffMagnet;

    // --- Sneak to move magnet to offhand ---
    if (isMainMagnet && player.isSneaking) {
      if (!offHand) {
        equip.setEquipment("Offhand", mainHand);

        // Clear mainhand slot
        inv.setItem(player.selectedSlotIndex, undefined);
      }
      continue;
    }
})```
idk what wrong with this it doesnt set the item to the second hand but it clears the item why does it skip the setEquipment step
subtle cove
#

u can have stick on ur offhand...

hazy kraken
subtle cove
#

today i learned try finally from copilot

safe stream
#

oh shit

#

i didn't know there was a keyword called finally

noble ibex
#

Is there a way to detect when the player middle clicks a block besides watching for changes in the player's inventory?

distant tulip
#

no

noble ibex
#

alright, thanks anyway

unreal saddle
#

[Scripting][warning]-12.87 MB of dynamic properties were saved during the last minute, exceeding the 10 MB threshold.

Ahmmmm

#

Solution for this error?

distant tulip
#

it is a warning, not error

#

try to reduce dp to bellow 10 mb per minute to remove it

round bone
unreal saddle
#

Yep ,In fact I already realized that I exaggerated with the system.run or simply system

unreal saddle
#

I find it too funny that I do this with the scripts.😹

distant tulip
#

sorry about?

unreal saddle
#

For confusing me between warning and error

distant tulip
#

ah, no worry

round bone
warped blaze
near siren
#

Did they change how you use typescript for scripting? Keep getting an error saying 'does not contain file [main.js]' (the file is named main.ts)

valid ice
#

You still need to compile the typescript into JavaScript; minecraft doesn’t do it for you

near siren
#

Oh I might have misspelled the file in the manifest. Also, I never realized it doesn't compile it, I've always just used bridge. for convenience and it does this

valid ice
#

Bridge probably has an auto-compiler in place for typescript

hazy kraken
#

I can get the typeId of redstone ore but not lit redstone ore, anyone know how I can get it?

dawn zealot
#

u should be able to?

hazy kraken
woven loom
#

any way to use localization key in debug text ?

warped kelp
#

Hey hey, Could someone point me towards how I could make an entity "strafe" or move backwards with scripts? I try with move_around_target and flee but they suck

woven loom
#

apply impulse @warped kelp

#

or knockback

warped kelp
#

I use apply impulse for knockback stuff and it doesn't seem to work on entities with a knockback of 1

timid zenith
#

Who has an addon to measure an example of how custom commands with /

torn lance
#

where can i get started for script api 2.0 like idk how this new custom components works, it is better to use than old custom components?

shy leaf
warped kelp
shy leaf
#

odd

warped kelp
#

Lemme try. Maybe it's the armor

warped kelp
#

It works fine, got it

shy leaf
#

bruj

warped kelp
#

Yeee.

warped kelp
# shy leaf bruj

What's a good impulse amount to make an entity "move backwards" from their target without like, overusing it?

I guess I could use my damage detection that activates a "move backwards" function with a remove score and scriptevent to move backwards, and it activates every 5 seconds with interval adding a score of 1

shy leaf
#

honestly

#

entity behavior

#

is probably the best way

warped kelp
#

Wuh

shy leaf
#

if theres even a good way to do it

#

i dunno, making mob behaviors via scripting in general does not sound great

warped kelp
#

My main problem is that move around target gives my entity zoomies, and flee from target makes my entity look like a coward..

#

Though I guess I'll do flee from entity

warped kelp
shy leaf
#

if the uh

#

avoiding entity is higher priority

#

then

#

yeah

woven loom
#

get blocks api is very fast

fair quarry
torn lance
fair quarry
#

Damn that's perfect, Recently I was trying to create an AI that plays Minecraft, but picking up blocks to do pathfinding was very laggy

woven loom
fair quarry
#

That is perfect.

woven loom
fair quarry
#

Ping me too!

woven loom
#

oki

woven loom
#

@torn lance @fair quarry

fair quarry
#

Thxxx

warped blaze
fair quarry
#

Lol he is posting this here too

woven loom
#

Nice adding idea

#

Addon

distant tulip
#

I wonder if adding world tick component to unloaded mob will make it tick

woven loom
#

Can we load a chunk with scripts @distant tulip

warped blaze
distant tulip
#

ticking area

woven loom
#

Any Work around

distant tulip
distant tulip
woven loom
#

Hmm need bp only way

warped blaze
woven loom
#

Let me delete one

warped blaze
#

so u don't lose them around the world

safe stream
#

is it possible to get the sound of a block?

#

like some method that would return the sound from blocks.json

woven loom
cinder shadow
#

Is my internet so slow right now that my microsoft learn site is exploding, or did they change something recently?

fallen hearth
#

Is it possible to have an entity that deals damage and has life based on mathematics? Because normally you have to use a group of components with health and attack already defined.

wary edge
#

Just access the health component and set it.

fallen hearth
#

If it is possible to use a value from a scoreboard as the maximum health value, it will help.

#
      "minecraft:health": {
        "value": "q.scoreboard(`my_score`)",
        "max": "q.scoreboard(`my_score`)"
      }
fallen hearth
#

@wary edge ?

warped blaze
#

does the onStepOn custom component triggers if i jump and fall on the block? or i must add the onEntityFallOn component too

wary edge
#

Fall on mostly exists to detect the min fall distance.

warped blaze
#

do you know a better way to get the entities standing on the block? I don't think using getEntities inside the onTick component would be so performant

warped blaze
#

yeah but it would trigger once, i want the player to be able to walk against the push (working like a treadmill), and it would stop after the first knockback if the player don't step off the block

wary edge
#

Unfortunately no.

#

Ticking it must.

warped blaze
#

well thx for the advice anyways

fervent topaz
#

hey

#

guys

#

how do u get the graphics mode

#

ik query.graphicsmodeisany

#

but

#

like

#

how

#

to set taht to a dp

#

and u cant use it in anim controler

meager cargo
#

Can I somehow modify Leather armor colors by script?
I know that there is dyable component for item, but it's not working for me.

distant tulip
distant tulip
thorn flicker
meager cargo
thorn flicker
#

#1067869374410657962

visual zephyr
#

sorry wrong channel

timid zenith
#
// Registrar el comando /kit
customCommandRegistry.registerCommand({
  name: commandNames.kit,
  description: commandDescriptions.kit,
  permissionLevel: CommandPermissionLevel.Any,
  cheatsRequired: false,
}, (origin) => {
  if (!origin.sourceEntity) return { status: CustomCommandStatus.Failure };
  const player = origin.sourceEntity;

  system.run(() => {
    if (!player.hasTag("kit")) {
      player.runCommand("function GetKit");
      player.sendMessage(`§8§l[ ${player.name} §8§l] -> §l§aKit reclamado exitosamente!!`);
      player.playSound("random.orb", { location: player.location, pitch: 0.5, volume: 10 });
      player.addTag("kit");
      return { status: CustomCommandStatus.Success };
    } else {
      player.sendMessage(`§8§l[ ${player.name} §8§l] -> §l§cEste kit ya ha sido reclamado!`);
      player.playSound("random.explode", { location: player.location, pitch: 0.5, volume: 10 });
      return { status: CustomCommandStatus.Failure };
    }
  });
});

How do I do to measure the item since with the runCommand it doesn't leave since it needs operator

honest spear
#

Who gets the meme?

round bone
# honest spear Who gets the meme?

I get it, and I can agree with that OOP is a strong option for a codebase, but pure JS will be still JS and it'll be just a piece of...

warped blaze
#

Is there any limit to the number of arguments we can put in a custom enum? (custom slash commands)

next frost
#

guys, ModalFormData supports labels?

next frost
#

oh thanks!

next frost
#

damn, this is really useful, how come I didn't check this out before, I've been using the api for a long time 🥀

dusky flicker
round bone
dusky flicker
#

and yet falls to the same problem

subtle cove
#

;compile js```js
const s = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
s.forEach((n, i, r) => {
r.delete(n)
r[i] = n
});

console.warn(s.size);
console.warn(s);

spiral umbraBOT
#
Program Output
0
Set(0) {
  '1': 1,
  '2': 2,
  '3': 3,
  '4': 4,
  '5': 5,
  '6': 6,
  '7': 7,
  '8': 8,
  '9': 9,
  '10': 10
}

warped blaze
#

can we get a block's cardinal orientation using getState("minecraft:cardinal_direction")?

open urchin
#

If the block has that state then yes

weary tapir
#

yo im lowkey hella confuzzled

#

does anyone know why my code doesnt do anything, im pretty sure ive linked everything perfectly

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

world.beforeEvents.chatSend.subscribe(function(data) {
world.sendMessage("echoing "+data.message);
})

#

im using server 2.2.0 btw

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

world.beforeEvents.chatSend.subscribe((data) => {
  world.sendMessage("echoing  "+data.message);
})```
open urchin
#

Chat send is in beta

weary tapir
#

ohhhhh

#

i have beta downloaded, how can i switch it over?

#

"dependencies": [
{
"module_name": "@minecraft/server",
"version": "2.3.0-beta"
}
]
}

warped blaze
open urchin
#

Yes, it's more old fashioned though

weary tapir
#

ya im used to it because i used to be a lua dev

open urchin
#

It does have some minor differences from arrow functions but it works the same in that situation

weary tapir
#

do i just enable beta apis and switch the server version in the manifest?

open urchin
#

Yes

weary tapir
#

alr

#

is newest beta 2.3.0-beta?

open urchin
#

I think so

weary tapir
#

aigth bett

open urchin
#

If not it will tell you in the content log

weary tapir
#

how the car do i a see the content log in minecraft

shy leaf
#

in settings, go to 'creator' and enable content logs gui

#

and set the log level to info

weary tapir
#

ah ty

open urchin
#

If you're on windows you can open it with Ctrl+H when it's enabled

shy leaf
#

also yes that

#

its a useful shortcut

weary tapir
#

lets go it workssss

warped blaze
#

can we get and/or set a horse's speed stat or jump height stat?

#

via script api of course

thorn flicker
devout sandal
#

Is there a way to see in a script what subpack resource pack is enabled?

devout sandal
jolly citrus
#

is there an equippable equivalent of playerinventoryitemchange

round bone
jolly citrus
#

i dont think it does because how would that work

#

oh wait

#

ill see i havent tested that before

#

thought it'd only work for actual inventory but it seems there's a playerinventorytype property

round bone
jolly citrus
#

no that wouldnt work

#

technically it would catch that yes,

#

but it would also catch anything else (for example dropping the item) unless you explicitly check e.g. is player equippable slot "chest" now this item?

round bone
midnight ridge
#

u mean cant?

round bone
jolly citrus
#

is it just me or is playerInventoryItemChange slow as hell

#

i get an item in my inventory and it fires like 8 ticks late

regal folio
#

This happened, and didn’t fix when I reloaded but it fixed itself when I rejoined.

weary tapir
#

anyone know why my script always gets an undefined?

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

function getHome(player) {
return player.getDynamicProperty("ftrhome:home");
}

function setHome(player) {
player.setDynamicProperty("ftrhome:home");
}

world.beforeEvents.chatSend.subscribe(function(data) {
const sender = data.sender;
const message = data.message;

if (message == ".home") {
const homeLocation = getHome(sender);

if (homeLocation === undefined) {
  world.sendMessage("You do not have a home location set");
} else {
  sender.teleport(homeLocation);
}

}
else if (message == ".home set") {
setHome(sender);
}
})

#

WAIT NVM

#

i figured it out

weary tapir
#

hey everyone

#

im back

#

and i have another error

#

absolutely no clue why this doesnt work

{
"format_version": "1.21.0",
"minecraft:item": {
"description": {
"identifier": "myaddon:test_gem"
},
"components": {
"minecraft:icon": "myaddon.test_gem",
"minecraft:display_name": { "value": "Heart Gem" },
"minecraft:consumable": {
"on_consume": {
"run_commands": [
"playsound mob.wind_charge.throw @p",
"attribute @p minecraft:health modifier add heart_bonus 2 add",
"clear @p myaddon:test_gem 1"
]
},
"use_duration": 16,
"animation": "eat"
}
}
}
}

#

doesnt throw an eror, just silently doesnt do anything

shy leaf
weary tapir
#

absolutely zero clue what that means :3

weary tapir
warped blaze
cursive fog
#

How do you make something that stores data

shy leaf
cursive fog
#

Apologies if im asking simple stuff
Im uhh thinking of a concept

shy leaf
#

no its not property as in component properties

cursive fog
#

Interesting

shy leaf
#

dynamic property simply stores string into your world storage

weary tapir
warped blaze
#

register your own and add it to your item's components

#

like

#
"components": {
  "berry:heart_gem_component": {}
}```
weary tapir
#

nice

#

no clue how to use that but it helps

shy leaf
#

oh wait

#

nvm i misread that

#

whoops!

weary tapir
#

once i have the component, how to i use it in scripts?

warped blaze
weary tapir
#

alright

warped blaze
# weary tapir alright
import { world, system } from "@minecraft/server";

system.beforeEvents.startup.subscribe(({ itemComponentRegistry }) => {
  itemComponentRegistry.registerCustomComponent("berry:heart_gem", {
    onConsume: (data) => {
      const { source: player, itemStack } = data;
      player.runCommand("bla bla")
    }
  })
})```
#

something like that

#

wait

#

wrap the runCommand inside a system.run()

#

forgot abt that

weary tapir
#

oh yeah

#

cause before events can access the server right? (read only?)

lethal bramble
broken pawn
#

didn't it way more simple?

warped blaze
broken pawn
#

hmm... looks like i have to learn custom registry now

weary tapir
# warped blaze ``` "components": { "berry:heart_gem_component": {} }```

how would i add the custom components to this? would i keep the minecraft:consumable and all that?

{
"format_version": "1.21.0",
"minecraft:item": {
"description": {
"identifier": "myaddon:test_gem"
},
"components": {
"minecraft:icon": "myaddon.test_gem",
"minecraft:display_name": { "value": "Heart Gem" },
"minecraft:consumable": {
"on_consume": {
"run_commands": [
"playsound mob.wind_charge.throw @p",
"attribute @p minecraft:health modifier add heart_bonus 2 add",
"clear @p myaddon:test_gem 1"
]
},
"use_duration": 16,
"animation": "eat"
}
}
}
}

#

kina forgot to ping sorry but @warped blaze seems to know what theyre doing

warped blaze
#

and everything inside it

weary tapir
#

ok tysm

warped blaze
#

@weary tapir i just checked, apparently the "consumable" component doesn't exist anymore, so if that doesn't work maybe you'd have to replace it with the "minecraft:food" component

#

i looked into the docs and it isn't there so idk

shy leaf
weary tapir
#

how do i do code blocks for longer messages?

#

never mind

#

so should i just remove the minecraft:consumable from this?

{
"format_version": "1.21.0",
"minecraft:item": {
"description": {
"identifier": "myaddon:test_gem"
},
"components": {
"minecraft:icon": "myaddon.test_gem",
"minecraft:display_name": { "value": "Heart Gem" },
"minecraft:consumable": {
"use_duration": 16,
"animation": "eat"
},
"crystals:heart-crystal": {}
}
}
}

warped blaze
weary tapir
#

alr

#

the pain of making a million uuids bruh 😭

warped blaze
#

someone made a manifest.json generator iirc

#

idk if it also generates uuids automatically

weary tapir
#

it says that no items use the custom component, even though i doubled checked the spelling and it set in my json file for the item under components "crystals:heart-crystal": {}

#

know why this might be @warped blaze ?

torn lance
#

its been long time since i touched script api, can anyone tell me if entityHitBlock event will fire when player hit block?

honest spear
#

yea

torn lance
#

thx

lethal bramble
#

in the api

torn lance
warped blaze
#

i was sleeping

empty yoke
#

But to create a chest the only way is to use an entity inside the block but I have seen that this prevents the block from breaking, there is nothing through scripts that can force the opening of the inventory of an entity?

wheat condor
empty yoke
wheat condor
empty yoke
# wheat condor then what are you trying to achieve?

I want the inventory to open when the player interacts with the block, as this would prevent the block from breaking. I looked at some content on the marketplace and saw that they used a workaround: interact with the block first and then interact again to open the inventory. As soon as you exit the inventory, the block reverts to the closed state and the dummy entity hides.

empty yoke
wheat condor
#

if you need help to save the items when deleting the entity i also got something that might help you #1252014916496527380

weary tapir
#

i don’t think we’re near time zones lol

subtle cove
# midnight ridge ha?

rhetorically speaking. but yeah it aint possible to have any item there thats not allowed on offhand

weary tapir
# warped blaze send your main.js and item json

main.js

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

system.beforeEvents.startup.subscribe(({ itemComponentRegistry }) => {
itemComponentRegistry.registerCustomComponent("crystals:heart-crystal", {
onConsume: (data) => {
const { source: player, itemStack } = data;
world.sendMessage("eaten")
}
})
})

test_gem.json

{
"format_version": "1.21.0",
"minecraft:item": {
"description": {
"identifier": "myaddon:test_gem"
},
"components": {
"minecraft:icon": "myaddon.test_gem",
"minecraft:display_name": { "value": "Heart Gem" },
"minecraft:consumable": {
"use_duration": 16,
"animation": "eat"
},
"crystals:heart-crystal": {}
}
}
}

shy leaf
#

if youre using custom components

weary tapir
#

really

#

thanks

#

ill try it

empty yoke
#

But is there a save limit for structures?

wheat condor
empty yoke
wheat condor
echo kindle
#
player.camera.setCamera("minecraft:free", {
        location: { x: player.location.x + (1 - (Math.random() * 2)), y: player.location.y + (0.25 + Math.random()), z: player.location.z + (5 - (Math.random() * 3)) },
        targetEntity: player
    });
player.camera.setCamera("minecraft:free", {
        location: { x: player.location.x + (1 - (Math.random() * 2)), y: player.location.y + (0.25 + Math.random()), z: player.location.z + (5 - (Math.random() * 3)) },
        offsetFromTargetCenter: player.location
    });

Someone can help me?
My camera don't wanna look at player, and I tried this two methods: targetEntity and offsetFromTargetCenter
(Sorry for my bad english)

woven loom
#

try facingLocation

#
player.camera.setCamera("minecraft:free", {
        location: { x: player.location.x + (1 - (Math.random() * 2)), y: player.location.y + (0.25 + Math.random()), z: player.location.z + (5 - (Math.random() * 3)) },
        facingLocation: player.getHeadLocation()
    });
#

@echo kindle

echo kindle
#

Thanks

woven loom
#

works?

echo kindle
#

I will test after

woven loom
#

oh

#

k

echo kindle
#

Going to play with my bf

weary umbra
#

guys is this a bug?

formValues returns everything header, divider, toggle but it should only return the values from toggle

[Scripting][warning]-{"night":true} [null,null,true,true,null,null,null,true,null]
export function settings(player) {
    let property = new Property(player)
    let quest = property.getProperty("settings", {}, "object")
    let ui = new ModalFormData()
    ui.title("§bSettings menu")
    ui.header("§bBattlePass Settings")
    ui.divider()
    ui.toggle("§7Enable Quest Menu", {defaultValue: quest.battlequest})
    ui.toggle("§7Enable progress", {defaultValue: quest.progress})
    ui.divider()

    ui.header("§bOther Settings")
    ui.divider()
    ui.toggle("§7Enable Night Vision", {defaultValue: quest.night})
    ui.divider()
    ui.show(player).then((data) => {
        let { formValues, canceled } = data
        if (canceled) return

        quest.battlequest = formValues[0]; 
        quest.progress = formValues[1]; 
        quest.night = formValues[2]; 

        console.warn(JSON.stringify(quest), JSON.stringify(formValues));
        property.setProperty("settings", quest);
    });
}
woven loom
#

its like that from start

weary umbra
#

when divider and header came out I didnt had this issue

#

thats why I was confused

woven loom
#

hmm

#

values are undefined right?

weary umbra
#

divider and header returns in formValues null but that shouldn't happen. Bc they cant return anything

warped blaze
#

those elements are included in the formValues array

#

as undefined or null

#

I can't remember tho

empty yoke
#

But some of you have the same problem with the projectile component: it doesn't behave as described in the documentation. Only if you use the runtime_identifier on the arrow does it behave correctly. For example, if I set gravity to 0, it's still applied and the projectile travels further only if I increase the power, but this makes the projectile almost invisible and the collision on the entities is absent in some directions or throws.

jolly citrus
#
(attacker as CustomPlayer).player.playAnimation("animation.scale_root", { players: [hitPlayer] });
#

how to stop the anim

somber sundial
#

also it makes sense because the index for the response values match the element index

#

you've got me to blame for them changing it back lol

fickle dagger
#

can I get player gamemode in entityHitEntity?

thorn flicker
round bone
untold magnet
#

hmmm, if i have two or three helmets of the same type, will the helmet.setDynamicProperty give a dynamic property for each one of the helmets? or all of them will share the same dynamic property?

round bone
untold magnet
#

is there a better way to do that? afaik dynamic properties takes storage or something, especially if u have like 999 of the same item

round bone
untold magnet
round bone
#

Dynamic Property is the best way to save data without using external DB's (which require additional "bloat" inside the add-on), so I would stick with it.

Sometimes it's better to have a simple class:

class ItemDataResolver {
    static #RARE_ITEMS = new Set(["minecraft:dirt"])

    static isRare(/** @type {string | import("@minecraft/server").ItemStack} */ item) {
        return this.#RARE_ITEMS.has(typeof item === "string" ? item : item.typeId)
    }
}
untold magnet
round bone
earnest meadow
round bone
#

JSDOC type of a param?

earnest meadow
#

isn't there like @param

round bone
#

@type can be interpreted as a habit from TypeScript, meanwhile @param is widely used for documentation in JS/TS and process of adding additional types.

earnest meadow
#

I primarily just use JSDOC, that's probably why it was new to me

round bone
earnest meadow
round bone
earnest meadow
dusky flicker
round bone
dusky flicker
#

no way theres how to use a db with it

#

imma make a package

untold magnet
round bone
dusky flicker
#

but isnt there a way to make so without /server-net

#

since its just for bds?

round bone
#

-# Except custom loaders and proxies, but I do not count these.

dusky flicker
untold magnet
#

like if the addon was activated in a server, will all players share the same value as this one or each player will have its own version of it?

wicked girder
#

Are tags or dynamic properties faster?

#

Like would it be better to have a boolean property or check if it has a tag?

round bone
weary tapir
#

ya and you can very easily directly set them and get them in code

echo kindle
#

Exist a way to apply damage per tick? Like a dps game?

#

With custom health?

round bone
honest spear
#

@honest spear

untold magnet
#

mhm

dusky flicker
woven loom
#

?

round bone
round bone
dusky flicker
#

bit operations truncate the number to 32bits

#

what could be done is to save strings as bit arrays

#

for you'd be able to have about 65k*32k

#

2billion

#

no wait

#

what kind of math did i just do?

#

its 16bits * 32768

#

524288 this thing

round bone
#

Oh, you just said it, lmao.

dusky flicker
wicked girder
woven loom
#

use profiler to test that

round bone
dusky flicker
#

since it acts as a array of chars

round bone
dusky flicker
#

it really wouldnt be a good idea to use arrays

warped blaze
#

if i use applyKnockback() or applyImpulse() to be pushed upwards while going at a certain speed horizontally, would i preserve my horizontal momentum?

woven loom
#

yes

scenic bolt
#

I noticed in a preview about a month ago that there was something about not needing to specify the script beta version in the manifest. How do you go about that, sorry if this is a dumb question

warped blaze
scenic bolt
#

ill test it

warped blaze
#

not released yet

scenic bolt
#

Yep just broke all my blocks when I did that lol

scenic bolt
scenic bolt
#

Does anyone know if this is in preview?

prisma shard
#

How do i detect clicking on a button in ActionForm

#

nvm im dumb its just the selection property

scenic bolt
lethal bramble
#

nvm

scenic bolt
lethal bramble
#

custom components are really limited rn ig

scenic bolt
#

true

shy leaf
#

they changed that???

pliant breach
#

guys is there any way to change the mob holding item using script. I tried using seEquipment but it only work on player somehow.

prisma shard
pliant breach
#

thanks

pliant breach
#

yeah it work now thanks bro @prisma shard

prisma shard
#

wow

#

looks cool

warm drum
#

Any good db with limitless string key-value support?

round bone
warm drum
round bone
warm drum
#

1GB of string data maybe

round bone
warm drum
#

The point is, it's a JSON stringify, so I need a DB that handle the abstraction of distributing them into thousand of dynamic properties, then concat them upon being called

round bone
warm drum
#

Bruh, if i could call http request, why would i ask for a db?

round bone
warm drum
round bone
warm drum
#

yeah

#

funny enough

#

i cant find any db that do that

subtle cove
#

just refactor the code into managing the necessary object instead of getting the whole object to stringify/parse

warm drum
#

well, not possible with my use case

dusky flicker
#

it will be pretty slow because of strings and js isnt that fast for byte manipulation(thanks to json)

#

but it will compress bytes and you can cache things

warm drum
#

this sucks

dusky flicker
#

you can store 65kb per dynamjc property

#

just implement paging on these

warm drum
#

thats nothing tbh

#

paging is the only option then

dusky flicker
#

normally 4kb

warm drum
#

btw, has no one made a paging system yet?

dusky flicker
#

i was really wondering in implementing an actual database on minecraft

#

it would be pretty fun

#

but sadly slow as hell

warm drum
#

who cares lol

dusky flicker
dusky flicker
warm drum
#

so http module is not an option

dusky flicker
#

i was asking this kind of stuff to a guy yesterday, it seems the only option is websocket

warm drum
#

websocket is another nightmare, i would rather stick with a paging system

dusky flicker
#

thanks to http

subtle cove
warm drum
#

but

#

the user could generate a huge amount of very dynamic data, so thats why i need a limitless key-value db

#

it only saves upon world exists too

dusky flicker
#

make a paging system and hash the key

#

that would be unlimited

warm drum
#

😭

round bone
dusky flicker
#

someone might have implemented it

warm drum
#

thanks guy

dusky flicker
warm drum
wary edge
#

Can we not dynamically update a run?

such as:

counter
system.run(()=>{counter++}, counter);
dusky flicker
#

function f(amount){
  stuff();
  system.run(()=>f(++amount), counter);
}
let counter = 0;
f(counter);
#

is this what you mean?

wary edge
#

I see I see.

wicked girder
#

How would I go about detecting when items are picked up?

#

Oop wait nvm forgot I had a if statement there

safe stream
#

how do you read an ItemStack id? (not typeId but the [data: int])

cold grove
safe stream
#

itemstack

#

I went with using hasItem arg cause i couldn't find anything about data on the doc

safe stream
#

no. it's data 😭

warped blaze
#

like

#

/give @s clock 1 1

safe stream
#

the type of a potion or an arrow or an enchantment book

safe stream
warped blaze
safe stream
#

Checking for the type of the arrow in the player's hand. The workaround that I'm using is for with hasItem and then checking for whether the execute command is returning true or not

#

so far it's working but i hate using commands in scriptapi

warped blaze
#

yeah ik you can get the potion type via script api, idk if you can get the arrow effect/type tho

safe stream
#

not sure

cold grove
#

Ahh i was reading and it should not work

onyx locust
#

whats the difference between setPropertyOverrideForEntity and setProperty?

onyx locust
wary edge
# onyx locust hmm? so setProperty changes every other same entities' property too? (i mean pla...

Correct.

https://youtu.be/Crs2lXPKsKM?t=600

Check this video out showcasing how ForEntity.

Wild how much is changing so fast
thanks to @SmokeyStack for creating the world, and thanks to Dasha for recording her side of that weird interaction haha

Follow my Twitter for video updates and early news! → http://twitter.com/ibxtoycat
Become a Channel Member to access exclusive videos & community posts, special emojis to use in the comment...

▶ Play video
coral ermine
#

can someone help why I can’t see any messages from people and they can’t see messages from me

warped blaze
coral ermine
#

Idk happened to me on multiplayer

open urchin
#

check your xbox account settings

coral ermine
untold magnet
# round bone Won't refresh it.

fixed, all i had to add is one dynamic property for the joined player, every player join into the world will start refreshing the ui, but the refresh thing will only happen to the new players, like after joining and refreshing the ui, the ui will refresh to everyone else but not u

#

it was a simple fix

silver agate
#

How can I make a system similar to /clear ${player} ${item} 0 1 using scripting methods?

woven loom
#

whats 0 1 ?

silver agate
#

0 is data
1 is amount

#

Data is like: oak = 0; birch = 1; etc.

#

That 0 is irrelevant

#

Btw

woven loom
#

I guess you have to map each data value to the corresponding state object.s

silver agate
#

That’s not what I meant

woven loom
#

Then you can find that item in your inventory and remove it.t

silver agate
#

What I want to do is: make a system that can remove items from the player’s inventory similar to /clear {player} {item} {data} {amount}

#

Where you only remove one item per time

woven loom
#

Yeah, but you'll need to know what item ur interested in

silver agate
#

Yes, i know

woven loom
#

Apart from that, the script is simple.e

silver agate
#

Let’s use ‘minecraft:apple’ and amount = 1. For example

woven loom
#

I can show you how to completely remove an item.y

#

U can improve on that

honest spear
silver agate
narrow patio
#

Is it possible to get text from a cmd block and also change text inside of it

narrow patio
#

:< darn

silver agate
# silver agate Yes please

Already got some functions made by chatGPT:

  for (let i = 0; i < container.size; i++) {
    const item = container.getItem(i);
    if (item && item.typeId === itemId) {
      if (item.amount > amount) {
        item.amount -= amount;
        container.setItem(i, item);
      } else {
        container.setItem(i, undefined);
      }
      return true;
    }
  }
  return false;
}

function addItem(player, container, itemId, amount = 1) {
  const newItem = new ItemStack(itemId, amount);
  const leftover = container.addItem(newItem);
  if (leftover) player.dimension.spawnItem(leftover, player.location);
}```
#

They work alright

subtle cove
#

the return true would be its limit that it's only gona clear the relative stack.

#

u can change it to clear the more than a stack if u want

edgy elm
#

Is there any other way to cancel damage? I am using damage sensor by editing the player entity but this cause conflict if they pair it with other addon for example RL CRAFT. I am making a pvp system but I don't have any idea since RL Crafts Player entity cannot be modify. If anyone has idea please tell me.

full idol
lilac glacier
#
import {
  Entity,
  world,
  system,
} from "@minecraft/server";


system.afterEvents.scriptEventReceive.subscribe(({ sourceEntity, id }) => {
  const view = sourceEntity.getViewDirection();
  const target = sourceEntity?.target;
  console.error(id);

  switch (id) {
    case 'cod:event_knockback':
      if (target) sourceEntity.applyKnockback({ x: view.x * 8.5, z: view.z * 8.5 }, 0.5);
      break;

    case 'cod:event_charge':
      if (target) sourceEntity.applyKnockback({ x: view.x * 10.5, z: view.z * 10.5 }, 0.5);
      break;

    default: break;
  }
});```

can anyone help me? my mob uses apply knockback and view direction so it can jump on its target and pounce them but the problem is that, even players in creative mode gets affected by view direction. 


is there a way to make it work only againt survival players?
#

and also, if it is probably possible too or impossible.

can we make the script so that. the mob can measure the height of its jump depending on the how far or near the target is?

warped kelp
lilac glacier
#

hmmmmm

warped blaze
prisma shard
neat hound
#

I have 2 world.afterEvents.worldLoad.subscribe...., each in a sep function. Will the contents process in order subscribed or do I need to combine to make sure desired processing order is maintained?

woven loom
#

i think it follows the order they sub in

lilac glacier
prisma shard
lilac glacier
gusty bramble
#

I can’t for the life of me figure out how to add an item to a container through a command.

-# yes I know /replace item exists but it’s not viable for my needs

Honestly at this rate I’d be happy if it just gave me the item temporarily because I can’t even get that to work properly.

I was using additem and it was saying it doesn’t have the permissions or something I don’t have the code as well I got annoyed and deleted it XD

twilit sky
gusty bramble
#

Yeah ok here’s the error

[Scripting][error]-ReferenceError: Native function [Container::setItem] does not have required privileges.    at <anonymous> (src/commands/pack.js:80)

and the logic

    for (let i = 0; i < inventory.size; i++) inventory.setItem(i, undefined);

    try {
      if (mode === "bin") {
        for (let i = 0; i < Math.min(code.length, 27); i++) {
          const id = code[i] === "1" ? "minecraft:iron_shovel" : "minecraft:glass_bottle";
          inventory.setItem(i, new ItemStack(id, 1));
        }
        player.sendMessage(`§aLoaded ${code.length} binary bits into shulker.`);
      } else if (mode === "hex") {
        const nibbleCount = Math.floor(code.length / 4);
        for (let i = 0; i < nibbleCount && i < 27; i++) {
          const bits = code.slice(i * 4, i * 4 + 4);
          const discId = discMap[bits];
          if (!discId) continue;
          inventory.setItem(i, new ItemStack(discId, 1));
#

Line 80 is:

    for (let i = 0; i < inventory.size; i++) inventory.setItem(i, undefined);
wary edge
gusty bramble
#

Yes i believe so

#

I am

wary edge
gusty bramble
#

system.beforeEvents.startup.subscribe(init => {
const packetCmd = {

That’s the start. So can i just switch it for that system.run instead?

#

Or can i just wrap that setItem part?

wary edge
shell coral
#

Is there a way to clear dynamic properties from a player which is offline?

#

doesn't seem like it

honest spear
#

i might be wrong but so far we don't have such a api

#

but if thats related to number you can use scoreboards

shell coral
#

yeah i need to clear all the dynamic properties when the uninstall command is run but cant do from a player which is offline

honest spear
#

Yea use scoreboard marker basicly create scoreboard and set it to 1 of you want to clear them on next join

#

that might work pretty well actually

shell coral
#

the problem is that when the uninstall command is run then it basically means the player wants to remove the behavior pack from the world

honest spear
honest spear
shell coral
#

yeah but not really ideal in my case, i am thinking on just using world object for everything for storing the dynamic properties but ignore the player object all together

gusty bramble
shell coral
#

will do that

wild topaz
#

Is it possible to make a script that will make players step up 1 block heights as easily as stepping up slabs and stairs without bumping into it, and make the feature only apply while sprinting?

shy leaf
#

if you want stairs kind of autostep, then its probably not possible from clientside

#

and it wont be as smooth as youd want with scripts

wild topaz
shy leaf
#

(of course chatgpt isnt good for this, it isnt a know-all thing)

wild topaz
#

Your right, I kinda overestimated it

shut citrus
#

Can I use scripts in sever or realms

granite badger
harsh robin
#

so i have a problem

#

i used chatgpt cuz i check how good ai is getting every few months and... It actually worked 😟

harsh robin
#

🙏

#

i learned all of ts for nothing

harsh robin
#

why? @distant tulip

distant tulip
#

Want to test it

harsh robin
#

Aight

#

i mean for what i asked was pretty simple i told it to only look at the microsft documentation and jaylys website and use version 1.21.11+ so jeb_shrug

harsh robin
distant tulip
#

using minecraft bedrock latest script api version make a script that listen for player selected slot changing, and get the item in that slot, then get the food component, if it is defined set the action bar of the player to display saturation and nutrition

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

// Listen for when a player changes the selected hotbar slot
world.afterEvents.playerHotbarSelectedSlotChange.subscribe((ev) => {
  const player = ev.player;
  const stack = ev.itemStack; // May be undefined if the slot is empty

  // Clear action bar if nothing is in the slot
  if (!stack) {
    player.onScreenDisplay.setActionBar("");
    return;
  }

  // Get the food component from the item (minecraft:food)
  const food = stack.getComponent(ItemComponentTypes.Food);
  if (!food) {
    // Not a food item — clear the action bar (or skip)
    player.onScreenDisplay.setActionBar("");
    return;
  }

  // Read nutrition and saturation modifier
  const nutrition = food.nutrition;
  const satMod = food.saturationModifier;

  // Optional: the applied saturation buff on eat is nutrition * satMod * 2
  // const satBuff = Math.round(nutrition * satMod * 2 * 10) / 10;

  // Show values on the player's action bar
  player.onScreenDisplay.setActionBar(`🍗 Nutrition: ${nutrition} | Saturation: ${satMod}`);
});

search and reasoning are both on
this is also really simple, i have a lot of cases where it will failed when things get complicated or it is trained on old stuff and it get conflicted

#

tho, not sure if this is perplexity thing or what, it took really long searching

distant tulip
#

i included the promt above

warm mason
#

So.. Essentially, you wrote code in Prompt, only not in JS, but in English. And GPT still didn't translate it correctly into JS.

harsh robin
#

@distant tulip

harsh robin
# distant tulip > using minecraft bedrock latest script api version make a script that listen fo...

this is what i got @distant tulip



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

world.afterEvents.playerHotbarSelectedSlotChange.subscribe((event) => {
  const player = event.player;
  const itemStack = event.itemStack;

  // If there is no item in the selected slot (empty hand), clear the action bar.
  if (!itemStack) {
    try {
      player.onScreenDisplay.setActionBar('');
    } catch (err) {
      // Errors can occur if called in early‑execution mode; ignore them safely.
    }
    return;
  }

  const foodComponent = itemStack.getComponent(ItemComponentTypes.Food);

  if (!foodComponent) {
    // If the item is not edible, clear the action bar and return.
    try {
      player.onScreenDisplay.setActionBar('');
    } catch (err) {
      // Suppress potential early‑execution errors.
    }
    return;
  }

  try {
    // Read the nutrition and saturation modifier from the food component.
    const nutrition = foodComponent.nutrition;
    const saturationModifier = foodComponent.saturationModifier;

saturationModifier × 2641407433635399L94-L96】.
    const saturation = nutrition * saturationModifier * 2;

    // Format the numbers for display. Use fixed decimals for saturation to
    // provide a concise read‑out.
    const satFixed = saturation.toFixed(2);

    // Construct the message shown on the player’s action bar.  The message
    // includes both nutrition and the computed saturation value.  `setActionBar`
    // displays text directly beneath the title and above the hotbar【838509993839380†L206-L223】.
    const message = `Nutrition: ${nutrition}, Saturation: ${satFixed}`;
    player.onScreenDisplay.setActionBar(message);
  } catch (err) {
    // If reading the component properties fails or the call is made too early,
    // clear the action bar to avoid leaving stale text.
    try {
      player.onScreenDisplay.setActionBar('');
    } catch (err2) {
      // Suppress nested errors.
    }
  }
});```
distant tulip
#

lol

#

i mean you are not getting anything worth by using ai alone
it is a tool and the result depend on who is using it

#

btw, welcome back Serty

warm mason
thorn flicker
warm mason
#

.-.

harsh robin
distant tulip
harsh robin
midnight ridge
inland merlin
#

Nice tool

lethal bramble
#

a quarter of the time, it doesnt work

#

the other 3 quarters, it produces badly structured code

honest spear
#

I have to agree with this statement

fallen cape
woven loom
#

I created an add-on using vsc's copilot without writing anything:p

#

Only prompts

round bone
#

All of vibe coders are making me less scary about my job in a future.

woven loom
#

Im not vibe coder tho

#

Just sayin

fallen cape
round bone
#

Keep vibe coding guys, it's the best to create a GitHub repo with all of your projects with only AI!

woven loom
#

I had to correct ai a lot

fallen cape
woven loom
#

Hm

#

Well then vibe coding is bad xdd

fallen cape
round bone
noble tiger
#

Is there a way to make players immune to fall damage while holding a certain item without applying Slow Falling

honest spear
fresh current
#

@honest spear

#

you think you can help me?

subtle cove
fresh current
subtle cove
#

tbh, im just peeking here some times if i can help on posts

subtle cove
fresh current
#

so no?

#

nope

#

problem just occured

subtle cove
#

most likely no, depends

fresh current
#

mhmk

noble tiger
#

Are custom components for items and blocks not a thing anymore?

fresh current
#

anyone can help me fix this into a chance you get it like when you spawn in its a 1% chance you get it instead of having a exp/level requirement for it?

gaunt salmonBOT
distant tulip
fluid jackal
#

Did I write the script correctly?

noble tiger
drifting ravenBOT
#
HCF Removal and Custom Components

The Holiday Creator Features experimental toggle has been removed. Along with it includes JSON block and item events. This functionality has been replaced with custom components.

Please take a look at the following links to learn more about custom components:

Bedrock Wiki

MS Docs

wary edge
pallid stag
#

Is it possible to block incoming damage?

thorn flicker
gusty bramble
#

It is possible to spawn items as if a mod died? Eg spawning the drops of a skeleton without the skeleton ofc and simulate looting too?

rich jacinth
#

Is it possible to do pathfinding for a mob with a script? I've come to the conclusion that normal entity pathfinding most likely won't work for what I'm doing and wanted to see if I could just use a script

distant tulip
#

check the A* algo from nox7 in #1067535712372654091

woven loom
#

It'll be slow.

rich jacinth
woven loom
#

If it works ,go for it 😅

turbid gulch
#

how to make in custom commands that parameter doesn have to be given?

woven loom
#

Optional?

turbid gulch
#

yes

woven loom
#

Use optionalParameters

#

Instead of mandatoryParameters

#

Other than that, everything is the same.

neat hound
#

registerEnum questions...

A name is defined, but never referenced. What if I register 2 or more, how does it know which to use.

the CustomCommandRegistry object is the same js system.beforeEvents.startup.subscribe((event) => { const ccr = event.customCommandRegistry; registerCustomCommands(ccr); });All my commands are registered in the function.

or... am I supposed to have a separate system.beforeEvents.startup.subscribe((event) for each command that has a different enum?

Does anyone have sample code with more than one command and they have different Enums and it works?

C.A.F.

#

Also... can I register anytime? I want to have some unlocking of commands to be able to even showup for the owner... so I do not want to register them until pwd entered... feasible?

round bone
round bone
neat hound
# round bone Could you show me `registerCustomCommands`?
/**
 * 
 * @param {CustomCommandRegistry} registry 
 */
export function registerCustomCommands (registry) {

    register_cls(registry);
    register_about(registry);

    if (pack.allowDebugOverride || debug.dev.debug) {   
        register_scoreboardsAllow(registry);
        register_debugEntity(registry);
        register_debugEntityActivity(registry);
        register_debugEntityAlert(registry);
        register_debugGamePlay(registry);
        register_debug(registry);
        register_debugLoadAndSpawn(registry);
    }
}```
round bone
neat hound
round bone
#

I don't want to be mean, but putting it all inside a single function (or even a class with private methods) would make the code so much cleaner.

open urchin
#

the enum that is used is based on the command parameter's name

round bone
#

Back in the topic - for safety, I'd recommend to make sure to register enums before any commands.

#

Also, can you show me, how do you declare enum parameters inside a command registry?

neat hound
# open urchin the enum that is used is based on the command parameter's `name`

This is the sample in Jayly's website.... the name is not the same ```ts
// Register an enum for command parameters
registry.registerEnum( "teleportTargets", [ "spawn", "home", "end", "nether" ] );

// Define a simple teleport command
const teleportCommand: CustomCommand = {
    name: "custom:teleport",
    description: "Teleport to predefined locations",
    permissionLevel: CommandPermissionLevel.Admin,
    cheatsRequired: true,
    mandatoryParameters: [
        {
            name: "destination",
            type: CustomCommandParamType.Enum,            
        },
    ],
    optionalParameters: [
        {
            name: "player",
            type: CustomCommandParamType.PlayerSelector,
        },
    ],
};```
open urchin
#

that example is wrong

round bone
open urchin
#

I think the enum also needs a namespace

round bone
#
registry.registerEnum( "custom:teleportTargets", [ "spawn", "home", "end", "nether" ] );

// Define a simple teleport command
const teleportCommand: CustomCommand = {
    name: "custom:teleport",
    description: "Teleport to predefined locations",
    permissionLevel: CommandPermissionLevel.Admin,
    cheatsRequired: true,
    mandatoryParameters: [
        {
            name: "custom:teleportTargets",
            type: CustomCommandParamType.Enum,            
        },
    ],
    optionalParameters: [
        {
            name: "player",
            type: CustomCommandParamType.PlayerSelector,
        },
    ],
};
round bone
neat hound
#

My mind blanked out the custom: part... okay, so as long as that matches. Ok I can stop freaking out now

solar dagger
#

Best way to setup a visible target lock on an entity?

wicked girder
#

Anyone know how to view the mcstats file?

stable shadow
#

Is it possible to get the name of the personalized chest using the anvil?

fair quarry
#

Baú

fickle dagger
#

if I have two textField, how would I search for the specific one that I want out of the two?

woven loom
#

they are ordered

fickle dagger
#

I'm gonna be honest I don't understand

#

I still don't know how to refer to only one of them

#

or both

woven loom
#

Show code?

fickle dagger
#

wait

#
world.afterEvents.playerInteractWithEntity.subscribe(({player, target, itemStack}) => {
    try{
        if(target?.typeId === 'felix:cash_register' && itemStack?.typeId === 'minecraft:paper'){
            const writeCashRegister = new ModalFormData();
            writeCashRegister.title('Write Receipt');
            writeCashRegister.textField('Receipt Title', 'Write title here');
            writeCashRegister.textField('Receipt Content', 'Write contents here');
            writeCashRegister.show(player).then((result) => {
                if(result.canceled) return;
                const [ textField ] = result.formValues;
                if(textField){ 
                    target.nameTag = textField;
                    player.sendMessage(textField);
                } else if(textField === ''){
                    target.nameTag = '';
                    player.sendMessage('');
                }
                target.playAnimation('buy');
            }).catch(error => { console.log(error, error.stack)})
        }
    } catch(e){}
});```
fickle dagger
woven loom
fickle dagger
woven loom
#

Np

halcyon phoenix
#

What's new these days?

#

did we get entityHitEntity before event?

thorn flicker
#

and entityHurt beforeEvent would be better imo

halcyon phoenix
halcyon phoenix
thorn flicker
halcyon phoenix
#

uhhhhhh lemme recollect..., since the vv update

#

like a month after that?

#

yeah

thorn flicker
#

i dont remember if this came after or before but we got events for relating to the player's inventory and hotbar.

#

the newest scripting thing I can think of is, getLightLevel method, getSkyLightLevel method

#

getBiome,

#

and in preview, there's a custom component event that allows us to detect when a block is destroyed (sources other than player), and a method to get an entity's bounding box.

#

what else...

#

loot table manager,

#

methods for getting block(s) that an entity is standing on.

thorn flicker
halcyon phoenix
#

thanks a lot, cheers.

thorn flicker
lilac glacier
#

so i just figured out how to import multiple scripts in the main.js but there's one issue.

these two scripts aren't working.

#

the first js is supposed to

#

make my mob jump backwards or forwards

#

meanwhile the 2nd js focuses on making it jump left or right.

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.

lilac glacier
#
import {
  Entity,
  world,
  system,
} from "@minecraft/server";


system.afterEvents.scriptEventReceive.subscribe(({ sourceEntity, id }) => {
  const view = sourceEntity?.getViewDirection();
  const target = sourceEntity?.target;
  console.error(id);

  switch (id) {
    case 'cod:event_back':
      if (target) sourceEntity?.applyKnockback({ x: view.x * -8.5, z: view.z * -8.5 }, 0.6);
      break;

    case 'cod:event_front':
      if (target) sourceEntity?.applyKnockback({ x: view.x * 10.5, z: view.z * 10.5 }, 0.6);
      break;

    default: break;
  }
});```
#

1st js:

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


system.afterEvents.scriptEventReceive.subscribe(({ sourceEntity, id }) => {
  const view = sourceEntity?.getViewDirection();
  const target = sourceEntity?.target;
  console.error(id);

  switch (id) {
    case 'cod:event_left':
      if (target) sourceEntity?.applyKnockback({ x: view.x * 8.5, z: view.z * -8.5 }, 0.6);
      break;

    case 'cod:event_right':
      if (target) sourceEntity?.applyKnockback({ x: view.x * -10.5, z: view.z * 10.5 }, 0.6);
      break;

    default: break;
  }
});```
#

2nd:

lilac glacier
gaunt salmonBOT
granite badger
lilac glacier
warped blaze
#

any idea why my getEntities() is so offseted? it affects players or entities that aren't even touching my block

    const { block, dimension } = data;
    system.run(() => {
      const center = block.center(), queryParams = {
        location: { x: center.x - 0.4, z: center.z - 0.4, y: center.y },
        volume: { x: 0.8, y: 0.05, z: 0.8 },
        excludeGameModes: [ GameMode.Spectator ],
        excludeFamilies: [ "lightning", "shulker" ],
        excludeTypes: [ "minecraft:painting" ]
      }, direction = block.permutation.getState("minecraft:cardinal_direction");
      for (const entity of dimension.getEntities(queryParams)) {
        entity.applyImpulse({ y: 0, ...pushDirections[direction] })
      }
    })```
lilac glacier
#

the console log was just added to see if the scriptevent works

warped blaze
granite badger
lilac glacier
#

my mob uses an event that

#

runs the scripts.

#
cod:hunter_lunge": {
                "sequence": [
                    {
                        "randomize": [
                            {
                                "weight": 40,
                                "queue_command": {
                                    "command": [
                                        "tp @s ~ ~ ~ facing ^ ^2 ^",
                                        "function hunter_lunge",
                                        "scriptevent cod:event_front"
                                    ],
                                    "target": "self"
                                }
                            },
                            {
                                "weight": 50,
                                "queue_command": {
                                    "command": [
                                        "tp @s ~ ~ ~ facing ^ ^ ^-1",
                                        "function hunter_lunge_back",
                                        "scriptevent cod:event_back"
                                    ],
                                    "target": "self"
                                }
                            },
                            {```
#

so yeah...

#

these scripts should be working by now.

granite badger
#

Try using applyImpulse rather than applyKnockback

lilac glacier
#

okay

fresh current
#

@granite badger can you help me fix this?

#

{
"pools": [
{
"conditions": [
{
"condition": "random_chance",
"chance": 0.01
}
],
"rolls": 1,
"entries": [
{
"type": "item",
"name": "op_asa:akumanomi_hiehie",
"weight": 1
}
]
},
{
"conditions": [
{
"condition": "killed_by_player_or_pets"
}
],
"rolls": 1,
"entries": [
{
"type": "item",
"name": "op_asa:bounty_aokizi",
"weight": 1
}
]
},
{
"conditions": [
{
"condition": "random_chance",
"chance": 0.1
},
{
"condition": "killed_by_player_or_pets"
}
],
"rolls": 1,
"entries": [
{
"type": "item",
"name": "op_asa:aokizi_haori",
"weight": 1
}
]
},

      }
   ]

}

#

its the bottom that i have a problem with

subtle cove
#

remove the comma and closing bracket

fresh current
#

ty

fresh current
#

hey @subtle cove

#

quick question

#

so i had extract my files from this addon so when im editing it in vsc it updates once i do /reload but that wasnt working i had to leave the game and rejoin for it to update + i had edited a bunch a files at once then once i log back in it didnt work ex the loot tables i edited them and they are not updating i even remove the mod then readded it

fresh current
#

nope

#

ima try but now

#

the scripts isnt even working

#

like they still droppign the items i edited them not to drop

#

in the loot tables

halcyon phoenix
subtle cove
harsh robin
#

Noooo

midnight ridge
#

where is my minecraft bedrock

fresh current
#

{
"pools": [
{
"conditions": [
{
"condition": "random_chance",
"chance": 5.0
},
{
"condition": "killed_by_player_or_pets"
}
],
"rolls": 1,
"entries": [
{
"type": "item",
"name": "op_asa:akumanomi_sorusoru",
"weight": 1
}
]
},
{
"rolls": 1,
"entries": [
{
"type": "item",
"name": "op_asa:bounty_bigmom",
"weight": 1
}
]
},
{
"rolls": 1,
"entries": [
{
"type": "item",
"name": "op_asa:akasi_yonko_bigmom",
"weight": 1
}
]
},
{
"conditions": [
{
"condition": "random_chance",
"chance": 5.0
},
{
"condition": "killed_by_player_or_pets"
}
],
"rolls": 1,
"entries": [
{
"type": "item",
"name": "op_asa:nikakubou",
"weight": 1
}
]
}
]
}

#

so would i increase the rolls?

#

actually im certained that the chance isnt even working

#

i even adjusted it to 25% and still no drops happeneing

scenic bolt
#

Anyone know how to use blockDestructionSource

#

Under the onBreak custom-component event

stable shadow
scenic bolt
#

I’m also curious as to if you can detect if it was destroyed by an explosion or just the tnt block or just an end crystal for example

scenic bolt
tender pier
#

Does anyone have a guide or something that helps me to learn about 2.0.0

#

I wanted to update my addon but i had no idea custom components were deprecated

#

And my addon is all broken lol

#

And now I don't know how custom components work

inland merlin
vast rune
#

i need to store splines/curves in a world. there are literally just class objects. how could i save them to make sure my entities still move on the same path, and on multiple different worlds?

candid otter
#

Anyone else got any ideas

terse pulsar
#

O cant get the entity damage with script like "entity.getComponent("minecraft:attack")"?

shy leaf
#

many attribute components arent exposed to scripting API yet

worldly heath
#

is it possible to repair a tool durability automatically?

round bone
halcyon phoenix
#

do I need to update my npm package?

#

I've been gone for months

round bone
halcyon phoenix
lucid dust
#

can anyone recommend me some good tutorials to learn the script api?

halcyon phoenix
#

minecraft bedrockLauncher says that the latest is 1.21.114

#

is that correct?

halcyon phoenix
#

dang 1.21.120 is the release version

terse pulsar
safe stream
lucid dust
safe stream
#

oh

round bone
shy leaf
#

but this is limited and cant be dynamic

halcyon phoenix
subtle cove
gaunt salmonBOT
halcyon phoenix
prisma shard
subtle cove
wicked girder
#

Any way to check if an entity is a baby?

shrewd garden
#

guys, any ideas on how to control the horse's movement by pressing a key? For example, when mounted, the horse walks at a normal speed, and when the control key is pressed, it runs.

thorn flicker
wicked girder
#

tyty

somber cedar
#

Shared folder