#Script API General
1 messages · Page 115 of 1
Sure ?
you can't.
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
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
"worldLoad event fires each time you do reload"
are you sure?
Huh? I tested and it worked, if i remember?
No?
shit I need to test again
i highly doubt it tbh, it is worldLoad and /reload doesn't reload the world
only /reload all will trigger that
Ok I've tested just now and yes, I was correct.

welp
everyday we learn smth new :p
yo is there a way to get the items on shelves?
there's still no way to detect potion type, correct
of potion item i mean
wait actually i think there is now
anyone know how to fix this errors?
can anyone give me a good projectile script?
fr ? how
I think you need to put inside of "
Yoo someone found out about fmbe
Yea I'm using them for more interactive shop holograms
pretty sure that’s an error that you can ignore
Yea I got that one to work but then a another one broke, and it made no sense
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?
Is it possible to make a notification using server-ui where it will appear and then disappear again?
server ui is just for forms
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.
form.show and closeAllForms but it'd be buggy
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
#1067535608660107284 message
oh hey i forgot i posted that before, thanks
lol
btw
ye, thx swell. it's actually interesting how i copied the link before I've seen ur reply 
i left then rejoined
yeah i noticed, what happened?
uhhh, cant sare much but i need the changes to reduce online stuff
i see
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?
all i can think of is to use getBlock function from dimension
what about with indirect methods like player JSON? would I have any more luck there?
i think that would be more complicated...
complexity is no longer the issue, my scripts die every time that a player joins and I have to check a 3x3 around them for lava 😭
ow
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
unfortunately I can't edit the json ui, well thank you it already helped
how would i force update a block?
like, for some reason a block (like a redstone component) is not properly reflecting its intended state
What is it?
a system for creating block displays using only commands. it was created like last year or something.
where can i find
Installation for @minecraft/server-net
Beta API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
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
import { beforeEvents as netBeforeEvents } from "@minecraft/server";
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
are you using server-net on your manifest
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
ah that was the issue
thx
beforeEvents doesnt even exist on @minecraft/server directly like that and I was asking for server-net
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
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?
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
I would wait for jigsaws.
.120 is likely in 2 weeks. We just entered .130
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.
Try if mojang’s hello custom command helps you in any way https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.CustomCommandRegistry.html
is there a way to get player ping on server-net
same happened to me for some reason earlier
I want my camera to see an entity as a third person, how can I do this?
How can I check when a player blocks an attack with a shield?
Discord search came in clutch
im specialized in this 
(tho you already figured it out sooo)
No.
is getLightLevel() not released out of beta yet?
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
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?
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?
I mean, admin menus are easy if you know what system your applying it to, I'd recommend you make your own, and if there's something you don't know how to do, u can look on that pack and copy the paste the part your trying learn to chatgpt and ask it to explain line by line
please do not use chatgpt to ask for minecraft scripting api 😭
chatgpt works. but u have to be very specific i mean very
yes you have to be very specific
and even then, its limited on info
and you basically have to feed the entirety of API documents for it to actually understand
ChatGPT barely works
But I'm newer to scripting, so I'm lost out if my mind
I js need a site with the functions😭
those two will help you
openai models are dumb
ok other ai models can't detect this exists. the addon devs keep their job
the addon devs keep their job
not for so long
its quite too much for the ai to browse all those objects imo
sending the typings would be more accurate for em
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
u can have stick on ur offhand...
I meant it more for understanding JavaScript syntax
today i learned try finally from copilot
Is there a way to detect when the player middle clicks a block besides watching for changes in the player's inventory?
no
alright, thanks anyway
[Scripting][warning]-12.87 MB of dynamic properties were saved during the last minute, exceeding the 10 MB threshold.
Ahmmmm
Solution for this error?
it is a warning, not error
try to reduce dp to bellow 10 mb per minute to remove it
Are you using a queue system?
Yep ,In fact I already realized that I exaggerated with the system.run or simply system
Sorry :V
I find it too funny that I do this with the scripts.😹
sorry about?
For confusing me between warning and error
ah, no worry
If you're using that large sets of data and it's an add-on for Minecraft network, you might prefer to use a bit more performant database engine than Dynamic Properties.
I've made literally that same thing some time ago, i posted it in #1046947779118895114
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)
You still need to compile the typescript into JavaScript; minecraft doesn’t do it for you
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
Bridge probably has an auto-compiler in place for typescript
I can get the typeId of redstone ore but not lit redstone ore, anyone know how I can get it?
u should be able to?
Its a blockstate.
ah, ty
any way to use localization key in debug text ?
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
Does it work with entities that have a knockback resist of 1?
I use apply impulse for knockback stuff and it doesn't seem to work on entities with a knockback of 1
Who has an addon to measure an example of how custom commands with /
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?
applyImpulse should do it regardless of knockback resistance
That's the thing, it does do it, but the knockback is noticeably weaker
odd
Lemme try. Maybe it's the armor
bruj
Yeee.
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
Wuh
if theres even a good way to do it
i dunno, making mob behaviors via scripting in general does not sound great
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
Question, do I give the avoid entity higher priority than melee? The melee is just to track enemy .3.
Build custom minecraft bedrock commands with ease
Here
get blocks api is very fast
No lag??
will ya share the code?
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
no lag!
That is perfect.
sure i will ping u
Ping me too!
oki
Fast block scan
-# scans coal blocks
how to use:
- sneak and use the stick
@torn lance @fair quarry
Thxxx
lol
Lol he is posting this here too
I wonder if adding world tick component to unloaded mob will make it tick
Can we load a chunk with scripts @distant tulip
isn't that component supposed to work as a small tickingarea?
Nope, commands only
ticking area
Any Work around
Yeah, but the question is, if we edited the mob file, does spawned and unloaded mobs get updated too or not
Custom mob
Hmm need bp only way
he posted it again LOL
Let me delete one
tamed pets should have the tick component imo
so u don't lose them around the world
is it possible to get the sound of a block?
like some method that would return the sound from blocks.json
Yes create and map each block id with its sound
Is my internet so slow right now that my microsoft learn site is exploding, or did they change something recently?
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.
Yes.
Just access the health component and set it.
could you help me do this?
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`)"
}
@wary edge ?
use jayly docs atp
does the onStepOn custom component triggers if i jump and fall on the block? or i must add the onEntityFallOn component too
Yes.
Fall on mostly exists to detect the min fall distance.
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
OnStepOn works.
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
well thx for the advice anyways
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
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.
there is a native script api thing for that
it only work on custom items
it it the case for a lot of stuff
food component
dyable component
they were answered in a post btw
Okay, I've used ItemComponentTypes for enchanting, and wonder if dyable is too. Thanks for answer
#1067869374410657962
sorry wrong channel
// 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
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...
Is there any limit to the number of arguments we can put in a custom enum? (custom slash commands)
I don't think so.
guys, ModalFormData supports labels?
oh thanks!
damn, this is really useful, how come I didn't check this out before, I've been using the api for a long time 🥀
thats just because js is totally garbage and that's the closest to structs we have on the language
And that's why TS has been invented.
classes are js feature
and yet falls to the same problem
;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);
0
Set(0) {
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'10': 10
}
#debug-playground 👍
can we get a block's cardinal orientation using getState("minecraft:cardinal_direction")?
If the block has that state then yes
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
import { system, world } from "@minecraft/server";
world.beforeEvents.chatSend.subscribe((data) => {
world.sendMessage("echoing "+data.message);
})```
Chat send is in beta
ohhhhh
i have beta downloaded, how can i switch it over?
"dependencies": [
{
"module_name": "@minecraft/server",
"version": "2.3.0-beta"
}
]
}
i thought their function(data) {} part was the problem, is it a valid syntax?
Yes, it's more old fashioned though
ya im used to it because i used to be a lua dev
It does have some minor differences from arrow functions but it works the same in that situation
do i just enable beta apis and switch the server version in the manifest?
Yes
I think so
aigth bett
If not it will tell you in the content log
how the car do i a see the content log in minecraft
ah ty
If you're on windows you can open it with Ctrl+H when it's enabled
lets go it workssss
can we get and/or set a horse's speed stat or jump height stat?
via script api of course
no
Is there a way to see in a script what subpack resource pack is enabled?
Trying to stop some scripts from running if they aren’t needed for the subpack that is selected..
is there an equippable equivalent of playerinventoryitemchange
Equipping an item does not trigger this event?
what
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
Technically, equipping an item removes it from main inventory, so it should trigger.
no yeah thats true but i mean one that'd like
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?
Probably an additional data manager would be involved to solve your problem.
It does not have wide range of usage, pretty useless in my opinion.
is it just me or is playerInventoryItemChange slow as hell
i get an item in my inventory and it fires like 8 ticks late
This happened, and didn’t fix when I reloaded but it fixed itself when I rejoined.
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
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
this is HCF format, which doesnt exist anymore
absolutely zero clue what that means :3
how can i fix that?
the part of "on_consume" and everything inside of it was part of HCF (Holiday Creator Features), that specific function was removed, so now you have to use scripts
How do you make something that stores data
dynamic properties?
Hmm
Doesnt it uses entity property?
Apologies if im asking simple stuff
Im uhh thinking of a concept
no its not property as in component properties
dynamic property simply stores string into your world storage
i’m new to this, how can i run a script when the player eats something?
custom components
register your own and add it to your item's components
like
"components": {
"berry:heart_gem_component": {}
}```
isnt this v1 custom components?
oh wait
nvm i misread that
whoops!
once i have the component, how to i use it in scripts?
lemme send you a small example
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
cuz the part that before events execute it in the tick is not allowed to modify/change server state
import {system, world} from "@minecraft/server"
world.afterEvents.itemCompleteUse.subscribe(({ itemStack, source }) => {
if(itemStack.typeId=="berry:heart_gem"){source.runCommand("")}
})
didn't it way more simple?
maybe, i personally prefer custom components
hmm... looks like i have to learn custom registry now
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
remove the "on_consume" part
and everything inside it
ok tysm
@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
practically the same but custom components are more practical
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": {}
}
}
}
check if it works first, if not, then change it
someone made a manifest.json generator iirc
idk if it also generates uuids automatically
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 ?
its been long time since i touched script api, can anyone tell me if entityHitBlock event will fire when player hit block?
yea
thx
btw, a player is an entity. and in case u are still not sure, player literally inherits from entity
in the api
totally forgot about that, since it was in February, 2025 last i touched script api
send your main.js and item json
i was sleeping
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?
Nope you cant force open an inventory, but you can make the entity be accessible only from one side of the block so you can break the block from behind
I understand, it's not what I was looking for, I'll try other ways
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.
However, it would be very convenient if they added the forced opening of inventories
oh that way..
you just have to use the PlayerInteractWithBlock event to grab the first right-click
then you spawn the entity on the block location so when you press right click again you will open the entity inventory
if you need help to save the items when deleting the entity i also got something that might help you #1252014916496527380
alright
i don’t think we’re near time zones lol
rhetorically speaking. but yeah it aint possible to have any item there thats not allowed on offhand
useless indeed 
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": {}
}
}
}
i think you need 1.21.90 for format version
if youre using custom components
But is there a save limit for structures?
Nope, the only limit is the number of characters you can use to name a structure (basically the limit is your pc)
So is it better to save the inventory within a structure using a unique ID using the block position, or save everything within a dynamicProperty which however has a character limit. If I use multiple dynamicProperties for each chest, would that be a problem? I saw that dynamicProperties cannot be deleted individually
Using the block location, dynamic property is much slower and complex to save items. Also you can’t delete dynamic properties but you can se the their value to null or undefined
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)
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
works?
I will test after
Going to play with my bf
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);
});
}
its like that from start
divider and header returns in formValues null but that shouldn't happen. Bc they cant return anything
idk why but that was recently added
those elements are included in the formValues array
as undefined or null
I can't remember tho
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.
(attacker as CustomPlayer).player.playAnimation("animation.scale_root", { players: [hitPlayer] });
how to stop the anim
this is correct, for the first version it didn't include non-input-field values but they broke backwards compatability with how it always worked on servers so they reverted that change
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
can I get player gamemode in entityHitEntity?
yes.
Filter out null values from the response:
const inputFormElements = formValues.filter((element) => element !== null)
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?
Dynamic Property is binded to a single instance of an item. If you have the same items in your inventory, they still have their own Dynamic Property values.
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
You want to bind Dynamic Property to an item with specific identifier?
no, a better way to save the item info without using dynamic properties, i dont think there is a better way tho
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)
}
}
its not possible to (detect when that item breaks or despawn or disappear or gets burned or fucked or anything bad happen to the item that cause it to vanish) to remove the item dynamic property so it wont take storage
I believe it's possible via item transactions and beforeEntityRemove event listeners.
interesting how u set the type of your param
What do you mean by a param?
JSDOC type of a param?
Both are correct, one is inline, more intented to be just for typing, meanwhile @param comes with an additional documentation.
@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.
I primarily just use JSDOC, that's probably why it was new to me
@type is also part of JSDoc, but it's a bit less popular than @param.
not that, but the habit of writing it like an inline. Usually people write function param typings using @param for readability
It's cleaner to write @type inline in my opinion, but if someone really cares about the placement of things like this - they should just move to TypeScript at this point.
I agree, though, JSDOC is already pretty accessible and does the typings like how TypeScript would do it
and is there a way to use external dbs?
/server-net package. I recommend using with a backend and caching to handle everything correctly.
i rather make my armor not wettable, like i can make them gets wet after being underwater or under the rain, but that will be a little too unstable, and may cause some performance issues, so i rather keep it as it is
Just send HTTP requests to a backend server that will communicate with a database.
WebSockets, nothing else won't work.
-# Except custom loaders and proxies, but I do not count these.
the only way then
so i have an array let smth = false; will this thing be applied to all players in the world or each one will have its own version of it?
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?
Are tags or dynamic properties faster?
Like would it be better to have a boolean property or check if it has a tag?
Dynamic Properties are better and more secure.
ya and you can very easily directly set them and get them in code
Behavior pack is binded to a server, not to a single client. If you’ll declare a global variable like in your example, entire code will share the same value that you have declared at the beginning of a file.
@honest spear
that means leaving and rejoining the server will not refresh my addons Ui, i would have to make it refresh the ui whenever a new guy joins to the server, after fully refreshing the ui, it will give that player something like another variable or dynamic property to prevent the ui from refreshing for that person after someone else joins the server
mhm
Won't refresh it.
with a single dynamic property you can have about 32 flags
?
Bitfields.
Isn't that number even bigger?
sadly no
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
Technically you can use a string, and just split and convert to an array.
Oh, you just said it, lmao.
a for of is sufficient
Yeah I know that, was more wanting to know which was faster
use profiler to test that
I know, but still a way to store more of them inside a single variable.
i mean, instead of converting to an array, simple iterate over the string
since it acts as a array of chars
Ohh, in this context. Sometimes it's „cleaner” to have an array, but for performance it's better to stick with raw strings.
it really wouldnt be a good idea to use arrays
if i use applyKnockback() or applyImpulse() to be pushed upwards while going at a certain speed horizontally, would i preserve my horizontal momentum?
yes
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
cuz iirc those were acting as if my momentum was 0 before pushing me in any direction
just use "beta" ig
ill test it
Yep just broke all my blocks when I did that lol
Thanks!
Does anyone know if this is in preview?
How do i detect clicking on a button in ActionForm
nvm im dumb its just the selection property
follow up question to this. Does anyone think this would be released as a custom component? If so that would be great so it could work with parameters
isnt there the onblockdestroy event for custom components?
nvm
I wish lol, would have jumped right on that
custom components are really limited rn ig
true
wait, really?
they changed that???
guys is there any way to change the mob holding item using script. I tried using seEquipment but it only work on player somehow.
not possible with scripts.
Maybe possible with commands like replaceitem though,
There is no eqquipable component for entities in scripts
yeah the command work
thanks
Any good db with limitless string key-value support?
Dynamic Property has a very high limit.
high != limitless
How many keys would you like to store?
1GB of string data maybe
Can you use /server-net module?
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
It'll be very inefficient, can you use /server-net module?
Bruh, if i could call http request, why would i ask for a db?
I just want to be sure. You really have to split it through thousands of props?
well, depend on how the player uses it, but to future-proof it, splitting would be the best
Dynamic Property is the best fit for this type of project, but it won't be good enough to handle that big operations I think.
just refactor the code into managing the necessary object instead of getting the whole object to stringify/parse
well, not possible with my use case
the best thing you could do is to create a real database
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
this sucks
normal databases use 4 up to 16kb per page
normally 4kb
btw, has no one made a paging system yet?
i was really wondering in implementing an actual database on minecraft
it would be pretty fun
but sadly slow as hell
who cares lol
i wonder the same
it'd be better to simply use http for so
its not on server
so http module is not an option
i was asking this kind of stuff to a guy yesterday, it seems the only option is websocket
websocket is another nightmare, i would rather stick with a paging system
thanks to http
to reduce ram usage, I just parse necessary objects. u cn cache the parsed object, and perhaps attach a method that once unavailable, make the object invalid
The thing is, I already cache almost all of them
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
i dont want to reinvent the wheel, so im asking if anyone has made it yet
😭
This is pretty easy, you won't reinvent a wheel if you'll rewrite a simple concept like pagination.
well, thats a good point
search for something on npm
someone might have implemented it
i dont think thats necessary, chatgpt could do that easily
thanks guy
you gonna repent doing this
nah
Can we not dynamically update a run?
such as:
counter
system.run(()=>{counter++}, counter);
only if you call the system.run over and over
function f(amount){
stuff();
system.run(()=>f(++amount), counter);
}
let counter = 0;
f(counter);
is this what you mean?
I see I see.
How would I go about detecting when items are picked up?
Oop wait nvm forgot I had a if statement there
how do you read an ItemStack id? (not typeId but the [data: int])
Do you mean entity id?
itemstack
I went with using hasItem arg cause i couldn't find anything about data on the doc
AUX id?
no. it's data 😭
he means the one you can get via commands
like
/give @s clock 1 1
the type of a potion or an arrow or an enchantment book
yeah
what's your use case? maybe there's a workaround
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
yeah ik you can get the potion type via script api, idk if you can get the arrow effect/type tho
not sure
Ahh i was reading and it should not work
I got this saved idk if it will help you
https://github.com/Carchi777/SuperStack
whats the difference between setPropertyOverrideForEntity and setProperty?
ForEntity is per player.
hmm? so setProperty changes every other same entities' property too? (i mean player)
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...
can someone help why I can’t see any messages from people and they can’t see messages from me
does this happen on realms? cuz I've been having this problem a lot
Idk happened to me on multiplayer
check your xbox account settings
what’s in there
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
👏
How can I make a system similar to /clear ${player} ${item} 0 1 using scripting methods?
whats 0 1 ?
0 is data
1 is amount
Data is like: oak = 0; birch = 1; etc.
That 0 is irrelevant
Btw
I guess you have to map each data value to the corresponding state object.s
That’s not what I meant
Then you can find that item in your inventory and remove it.t
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
Yeah, but you'll need to know what item ur interested in
Yes, i know
Apart from that, the script is simple.e
Let’s use ‘minecraft:apple’ and amount = 1. For example
Yes please
Is it possible to get text from a cmd block and also change text inside of it
Not possible.
🙁
:< darn
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
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
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.
not that I am aware of
Does this actually work? I can't get it to actually see entities at all, I've tried everything, always 0 https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/dimension?view=minecraft-bedrock-stable#getentitiesfromray
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?
You could try make several different powered jumps, and depending on the distance, run a powered jump specifically.
Someone could prolly do it better, but if you use "execute if entity @e[r=8] run script event "cod:8 block jump"
"execute if entity @e[r=4] run script event "cod:4 block jump"
And so on
hmmmmm
it should work, maybe we could help you if you share some error logs or a piece of code
You can get players which are in survival, by doing:
world.getPlayers({ gameMode: "Survival" })
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?
i think it follows the order they sub in
didnt see this. thanks a lot
Having multiple events of the same kind is not a good practice, They will try to run at same time as world loads, and if you want to maintain the processing order of your code, just put in same event.,?
i mean.... if i add this my hunter will only jump at survival players?
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
Most likely, it's because you were calling .addItem() in read-only mode.
Surround it with system.run() and it should work.
Like this:
system.run(() => {
container.addItem(yourItem)
})
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);
Im going to assume you're running this in a beforeEvent.
You need to wrap it in system.run
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?
Yep
Is there a way to clear dynamic properties from a player which is offline?
doesn't seem like it
i might be wrong but so far we don't have such a api
but if thats related to number you can use scoreboards
yeah i need to clear all the dynamic properties when the uninstall command is run but cant do from a player which is offline
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
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
Ahh, well it still the same thing almost, basicly if you remove the behavior pack then the data are not accesible anymore, and if you add it back then the data will be deleted once the player joins
you can use world dynamic properties and store keys like player_name:keyname
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
yeah
Thanks!
will do that
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?
i tried this, but had no luck
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
Oh crap, I've been trying for a while now and even chat gpt couldn't do it😭
(of course chatgpt isnt good for this, it isnt a know-all thing)
Your right, I kinda overestimated it
Can I use scripts in sever or realms
short answer: almost yes
long answer: https://jaylydev.github.io/scriptapi-docs/latest/#platform-differences
so i have a problem
i used chatgpt cuz i check how good ai is getting every few months and... It actually worked 😟

we are cooked
🙏
i learned all of ts for nothing
What module did you use
Chatgpt 5 Payed version agent
why? @distant tulip
Want to test it
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
tho to be fair i asked it something VERY simple so
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
What did you ask it?
i included the promt above
🍿 👀
So.. Essentially, you wrote code in Prompt, only not in JS, but in English. And GPT still didn't translate it correctly into JS.
@distant tulip
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 × 2【641407433635399†L94-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.
}
}
});```
The only thing I agree with
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
thx
wb
Dude, i just said i ONLY use it to test the progress. i dont use ai to help me code im not a vibe coder.
i didn't say i am against using it
i dont like ai
so can i make a new item and give it this ability?
You should vibe code, its very handy saves alot of time
Nice tool
no, definitely dont vibe code.
a quarter of the time, it doesnt work
the other 3 quarters, it produces badly structured code
I have to agree with this statement
You shouldn't vibe code
AI is good for producing small snippets of code but anything >100 lines is likely not going to work + the fact that it's not that good with the bedrock APIs
All of vibe coders are making me less scary about my job in a future.
cool
but vibecoding is not looking at the code
Keep vibe coding guys, it's the best to create a GitHub repo with all of your projects with only AI!
Ohh
I had to correct ai a lot
Even if you look(meaning like you understand and read it) at the code the AI produced and you don't just approve any changes that's not vibecoding still
It is
Actually, it's very bad. Vibe coding skips lots of concepts, including security, which results in very bad products overall.
Is there a way to make players immune to fall damage while holding a certain item without applying Slow Falling
it works if you don't have to touch the coder anymore ever
u can ask those who are expert in items, cus I'm def not, unfortunately
are you a expert cause i need help with something rq
tbh, im just peeking here some times if i can help on posts
have u posted about it?
most likely no, depends
mhmk
Are custom components for items and blocks not a thing anymore?
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?
Installation for @minecraft/server
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
Installation for @minecraft/server-ui
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
they are
just changed to be more customizable
How are they done now? I only ask because when checking out the item documentation, the custom component component was listed as deprecated
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
- Block Events
- Block Events Migration to Custom Components
- Item Events
- Item Events Migration to Custom Components
MS Docs
@noble tiger
Is it possible to block incoming damage?
no.
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?
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
check the A* algo from nox7 in #1067535712372654091
It'll be slow.
You know any faster ways of doing it? If not I'll just go with what Minato sent
If it works ,go for it 😅
how to make in custom commands that parameter doesn have to be given?
Optional?
yes
Use optionalParameters
Instead of mandatoryParameters
Other than that, everything is the same.
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?
You can only register inside startup event, so no - you can't.
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);
}
}```
Pretty messy codebase. Do you register any enum before a command?
I did inside the function where it is defined, then it occurred to me to go check. I was not using enums before, but want to now and would need 2 different ones.
ANd what do you mean by messy codebase, how does that help me?
It's pretty hard to get through your codebase if you use different naming conventions and you split so much of stuff between functions.
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.
the enum that is used is based on the command parameter's name
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?
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,
},
],
};```
that example is wrong
You have to provide the exact names as your enums are.
I think the enum also needs a namespace
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,
},
],
};
Yes, it does.
My mind blanked out the custom: part... okay, so as long as that matches. Ok I can stop freaking out now
Best way to setup a visible target lock on an entity?
Anyone know how to view the mcstats file?
Is it possible to get the name of the personalized chest using the anvil?
Baú
if I have two textField, how would I search for the specific one that I want out of the two?
they are ordered
I'm gonna be honest I don't understand
I still don't know how to refer to only one of them
or both
Show code?
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){}
});```
here
const [ title, content ] = result.formValues;
oh, it's something like that? got it will try and thank you 🙏 🙏 🙏
Np
no
and entityHurt beforeEvent would be better imo
oh yeah that
nothing new as of now?
I dont know how long youve been gone.
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.
that's all I can think of
you can check this out to compare versions
https://stirante.com/script/diff.html#%40minecraft%2Fserver/2.2.0/2.5.0-beta.1.21.130-preview.22
thanks a lot, cheers.
going back into the shadows? lol
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.
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:
-# ping me once you got a solution
No errors in [code](#1067535608660107284 message)
Need content log
strangely there aren't any errors.
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] })
}
})```
the console log was just added to see if the scriptevent works
i think I'm using the volume parameter correctly
How do you run it, i.e. what command
the /scriptevent command.
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.
Try using applyImpulse rather than applyKnockback
okay
@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
remove the comma and closing bracket
ty
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
have u tried /reload all
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
yeah, college is nuts
||i'd prob start from scratch again before goin nuts||
Noooo
where is my minecraft bedrock
ok i fixed it but now i ran into another problem im pretty sure this script is rolling 1 so if you get either item it stops rolling right? if so i want it so even if you get the 100% drop which is the bounty you still get the chance to get 5% drops
{
"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
Anyone know how to use blockDestructionSource
Under the onBreak custom-component event
Documentation for @minecraft/server
Does this event work for vanilla blocks?
It says it gets the block the caused the destruction, however when I run it in console warn it’s undefined
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
onBreak is a custom component, so not for vanilla blocks
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
Introducing Custom Components | Microsoft Learn https://share.google/zvIo2Wz8fRXePZKiA
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?
O cant get the entity damage with script like "entity.getComponent("minecraft:attack")"?
you cant
many attribute components arent exposed to scripting API yet
is it possible to repair a tool durability automatically?
Add .toString or .toJSON method and stringify the object and save the result inside a Dynamic Property.
Yes, you should update definitely.
I forgor how to update
can anyone recommend me some good tutorials to learn the script api?
it's 1.21.120
Any other way?
both ms store and mc launcher say 1.21.114.1 for me
you'll have to reinstall, that's what i did (make sure to backup everything in com.mojang)
oh
Check for latest version of NPM.
editing entities to give them component groups and triggering events to switch the components
but this is limited and cant be dynamic
sorry but i haveno idea how to do it
Installation for @minecraft/server
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
I just run this at cmd right?
How do u show that in vscode
Any way to check if an entity is a baby?
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.
check if the is_baby component exists.
tyty
Shared folder
more specifically it's this https://jaylydev.github.io/posts/bedrock-gdk/#restore-your-data
