#Script API General
1 messages · Page 109 of 1
im doing something similar with a project, that has to do with food nutrients
which allows people to add stats with behavior packs without directly editing the addon
you can setup nutrient values on food items
interesting
custom command?
also has it
im using custom commands because I think it'll be way easier to configure that way, so an addon creator can setup a function for their addon to be compatible with my addon
because it were to be in server ui... cant really do that, and commands are easy to understand.
i think its doable with server ui
well the readability would be terrible considering the nature of server forms
dynamic properties are not readable from other addons though
there goes my system crumbling down
😭
ill figure it out
you can try this
idk what this is.
inter-pack communication
but uh
the repo doesnt have docs yet
im not a professional scripter or anything but it feels nice using things you make
I go insane more but thats fine
I bet it is
oh wait I know what my idea was
they dont need to access the dynamic properties, they just need to trigger the custom command when my addon is installed
so they either need to make a custom command, or a function, like I said, just to trigger my custom commands.
what about scriptevent?
well scriptevent can be shared across behavior packs
im looking into a way better to config so its not one item at time, per command
custom commands can be trigger through the runcommand method right?
yep
theres no problem then.
its an interesting concept tho
we have another way for packs to communicate with each other
and its custom command
Script events are still the best way.
anyone know if customcommandregistry has changed in the past 2 updates?
Not that I know of. What's your issue?
i made a post about it i cannot fix this no matter what so far nobodys been able to help me
I don't think it has
bruh wtf is wrong with this shit
imagine if Mojang gave us more json ui support in script api
But why?
like get data from ui and send the data to the script api
for example check if your hovering your mouse over a specific button and then the script api gets that and you run stuff accordingly
hello minato i see u
Hello to you too
gtg, lol
can i steal your pfp
yes:
world.beforeEvents.worldInitialize.subscribe(initEvent => {
initEvent.itemComponentRegistry.registerCustomComponent('pm_black_hole:trigger', {
onUse: e => { e.source.runCommand("function black_hole"); },
});
});
hey guys, do you have any ideas what doesn't worked
Its been moved to system.beforeEventd.startup
thank you it worked
Imagine if Mojang would force people to use TypeScript...
i want them to support ts
By them you mean community or Mojang?
I would love that honestly.
as an option, forcing ts sound like a bad idea
I am good enough with vanilla js
are there any workarounds to obtain an entity's target through scripting?
Yo what is the best way to store entity data? I'm trying to make a item that stores an entity, but without losing its data
I will probably use structures
Not without using beta.
we decided to go an alternate route that only requires us to detect whether or not it has a target
while (true) {
world.getDimension('overworld'). spawnEntity('minecraft:fox', {x: 0, y: 0, z: 0});
}

Consider this a warning
Just a crasher
this using clearVelocity method?
😋
lol I have made add-ons for that add-on before
behavior pack animation controller
Yes
structures are the only possible way to do it really
ive heard about it but
i actually dont know how it went
I'm wondering if there's any way to summon a firework with custom parameters like it's duration, and pattern.
Is this possible?
y'all
i feel like i am gonna go insane
ima make a post
can anyone help me understand the black magic???
https://discord.com/channels/523663022053392405/1411636011318120489
anyone know any known issues with beforeEvent Startup
no
what are you facing?
an issue with beforeEvents startup
really?
yes#
did you make a post?
yes
what did you do to confirm that it wont fire?
can i have the link?
2 days of trying to fix it with help
look in my post
@thorn flicker so im testing it right now...
this is weird as hell
its not 20 per breaking block
but its rather inconsistent
simply swinging in air fires the event once
but attacking(??????) or dropping an item fires it two times for me
Lot of stuff trigger it twice, fishing and so on
one thing thats certain is that the amount of triggers depend on the client's framerate
Huh
normalising typeids?
hey
Hi
Hello!
Yo
sup
quick question y'all
do simulated players have a chat function other than .chat?
because it doesn't seem to send anything in the chat.
I don't think so.
if not run /say from it
// ...
if (!bot) return print(source, `§cBot §6'${botName}'§c not found.`);
const msg = extra || "Unknown message";
bot.chat(msg);
print(source, `§3Bot §b'${botName}'§3 said: §7${msg}`);
// ...
it tells me that the bot sent the message and no error happens
that's not the issue
i can do:
world.sendMessage(`<${bot.name}> ${msg}`);
but the thing is, this wouldn't fire the chatSend event
does the .chat method fire the chatSend event??
i don't know, but i assume so.
try /say 🤷♂️
alr, sense it is not the same as send message, /say actually make the entity say so
it doesn't trigger chatsend
wait, while i am at it. let me test out the .chat method if it triggers the chatsend event
if you are wondering, this is what i used:
bot.runCommand(`say "${msg}"`);
also no
oh well
i guess world.sendMessage it is.
/w @a message?
these won't trigger probably but i'll try
The only thing that triggers ChatSend*Event is SimulatedPlayer.chat
.
nope
welp
yeah the method is bugged, it legit is supposed to send the message. if it ain't sending anything then chances are, it won't trigger chatsend.
i am just gonna keep it in until moyang decides to fix it
when an admin tells me a bot is sending messages twice i'll remove the world.sendMessage call.
nope, just a boolean property and two events
/say and anything with / is handled differently then a regular chat message
Even when it is from chat?
Ye
That's rude, i was watching
🤖

Are here some coders? I need help with a custom scoreboard
what is the issue you're facing?
also bruh, i have been typing my whole pack that player id is number | string
apparently it's only string??
numerical string
such id is relevant to entity.scoreboardIdentity.displayName
also used on world.getEntity
if (coins >= cost) {
removeScore(player, "Coins", cost);
const itemStack = new ItemStack(chosenItem.id, amount);
if (chosenItem.customName) itemStack.nameTag = chosenItem.customName;
inventory.addItem(itemStack);
player.sendMessage(
`§aPurchase Complete! Bought §e${amount} ${chosenItem.name}(s) §afor §e${cost} Coins§a.`
);
player.playSound("note.pling", { location: player.location });
} else {
player.sendMessage(`§cNot Enough Money! You need §e${cost} Coins§c.`);
player.playSound("note.bass", { location: player.location });
}``` how would i go about making this give the ammount of items even if its a non-stackable item
loop through the amount if it isnt stackable.
im not good at coding could u please give more in depth or example
if (!item.isStackable) {
//loop
} else {
//add item like u do
}
is there any way that i can get the world's seed using js?
loop?
?
what do i place within loop
wait a min
if (!itemStacck.isStackable) {
while (amount) {
inventory.addItem(itemStack)
amount--
}
} else {
inventory.addItem(itemStack)
}
this should do ig.
this does not work
what makes it not work btw
nvm, gamerfile's suggestion should work, no?
😔
commands support amount for none stackable
literally M9 had me go through minecraft all over again
how do i make a command give the ammount (which is not constant)
just with ${amount}?
no but i mightve used it wrong
the last prob lacked the amount
all i had to do is replace the inventory.addItem(itemStack); with it right
`give target id ${amount}`
the else part
Do whatever you want
that is terrible advice
@winged gullhi crafter
h i
i wish the script api was mostly asynchronous
?
export const give = (player, itemStack, amount = 1) => {
const inv = player.getComponent('inventory').container;
let leftover;
const addItem = (amt) => {
let item = itemStack.clone();
item.amount = amt;
if (!leftover) {
(item = inv.addItem(item)) && (leftover = true);
}
item && player.dimension.spawnItem(item, player.location);
};
const maxAmount = itemStack.maxAmount;
if (maxAmount === 1) {
while (amount-- > 0) {
addItem(1);
}
}
else if (amount <= maxAmount) addItem(amount);
else {
while (amount > maxAmount) {
addItem(maxAmount);
amount -= maxAmount;
}
if (amount > 0) addItem(amount);
}
};```use it like```js
const itemStack = new ItemStack(chosenItem.id);
if (chosenItem.customName) itemStack.nameTag = chosenItem.customName;
give(player, itemStack, amount);
i did it already thanks
Read the context
I did, but that can also be done without a laggy command.
my bad lmao i keep forgetting
._.
ill prob do it for the next release
/**
* @param {Entity} entity
* @param {ItemStack | ItemStack[]} items
*/
function giveItem(entity, items) {
const inv = entity.getComponent('inventory')?.container;
if (inv == undefined) return;
if (!Array.isArray(items)) items = [items];
for (let item of items) {
if (item == undefined) continue;
item = inv.addItem(item);
if (item) try {
entity.dimension.spawnItem(item, entity.location);
} catch {}
}
}
Use world.afterEventEntitySpawn
So I need some knowledge on what causes more lag:
I run a bunch of like scoreboard checks for each entity in the world each tick.
If using scripts what lags more in entity.hasTag, scoreboard checks or getting and setting dynamic properties.
Also I heard tags cause lag in commands what about in scripts.
U can test it urself with profiler
Start profiler try all the meathods few times then stop and view the profiler file in vscodd
Is there any difference between onUseon of custom component and playerInteractwithBlock?
you get the swing interaction with onUseOn
and there's the isFirstEvent property for playerInteractWithBlock
which can be used to see if you are holding interaction or not
Does onUseOn ignore interactive blocks? For example, anvils, among others? Of course, if the player is not crouched
no
Ah, in this case then I should define it manually, I was using playerInteractWithBlock but it executes even when I interact with interactive blocks without being crouched
Tnx a lot,
That just seemed like a lot of work,and I was hoping someone had already done that
Is it possible to remove knockback when getting hit by a projectile?
I think entity.applyKnockBack({0,0}), after getting hurt should cancel it
I used another method with date.now() to get the milliseconds for running each stuff 1000 times,
Tags >dynamic properties> scoreboards with scripts to reduce lag
Though I think hasTag takes more ms than removeTag and addTag and to be fair I also had few tags which might have been why they where so low
But it's prolly better to use entity.addTag() than if(entity.hasTag() ) entity.addTag,
But scoreboards eat tps with scripts to summarise
How can I create a command with a parameter for only one enum entry?
Using profiler is easy u just need to run the command 2 times
Ok I'd save that for later,what do you normally use profiler to do BTW?
Try clearing velocity when they’re hit.
entity.clearVelocity();
can it do give(player, new ItemStack('ender_pearl'), 1234)?
Wouldnt that throw an out of bounds error
would it...
ahem, the context
read it first
It gives u the list of things taking longer time
Is it possible to get a nametag of a mob like a named nametag thing and set their nametag to smth custom?
yes
Is it a bug that .runCommand can't use the [] data? /setblock ~ ~ ~ ladder["facing_direction"=0]
Thats not what it says. Its likely not a the right block state.
I can copy the command it runs and use it fine, but doing it through scripting causes the error and it rejects all [] arguments
Has anyone else experienced the inability to use transition in and out of free cameras in the camera command?
try replacing "=" with ":"
AWESOME! Thank you!
that's the old command syntax
you need to update your min_engine_version in your pack manifest
Ahh that makes more sense, I still had it set to 1.20
I've read somewhere that the runCommand method uses the old execute syntax, is it true?
it uses whatever the command syntax was in the min_engine_version you have specified
Yes, you can just use Entity.nameTag property.
thanks
You can read it and set.
Try searching in documentation first, sometimes you can find an answer here faster than someone might reply.
How do I generate structures in specific coordinates as soon as I enter the world? Is it possible?
yeah as long as the area is loaded
Hm
@pallid stag
world.afterEvents.itemUse.subscribe((ev) => {
const { itemStack, source } = ev;
const itemId = "minecraft:compass";
const command = "say this is baller";
if (itemStack?.typeId !== itemId) return;
source.runCommand(command);
})
this is what you can use for now
I don't understand anything about the code, and my addon has things that if I pass them to the script, it will only make it more complicated, just look
It has a timeline where it is timed from the use of the item, identifying scores, tags to be able to execute what I want
I'll wait a little longer to improve my scripting knowledge.
@shy leaf I'm going to practice scripting now, but first I need you to ask a question (sorry for marking)
sure, go on
sure, but the version you are using there is outdated
Version of what?
Which one would be correct?
server-ui is not needed if you are not planning to make UI forms
thats a good start
but the issue here is that it does not know when to send the message
so you might not be able to see the message when you load into the world
I learned that I always have to put import (world) from "@minecraft/server";
and you'll get a privilege error in v2
In the beginning
yes because thats how you create a script environment for your world
you tell the game that youre using this script file
Oh
How could I see the message?
youll have to add a way to send the message
this is what "events" are used for
the problem is the message tries to send when the system starts up, but you are not loaded into the world yet
when you load into the world, you wont see it in chat
yep, when you start a world, the codes in the script will be ran once
So I need to use events
and like I said it wont work in the first place like this if its script v2
Hum
event listeners.
there's listeners for specific things like, when an entity gets hurt, when a block gets broken, ect.
you can find everything here
https://stirante.com/script/server/2.1.0/index.html
Documentation for @minecraft/server
Can I use this world.afterEvents.playerPlaceBlock.subscribe((event) => {};
this is probably easier to read
yes you can
thats preview though
oops
forgot to switch
theres also beforeEvents
you should check this out before using beforeEvents, which also explains the privellege error I was talking about with world.sendMessage()
https://wiki.bedrock.dev/scripting/privileges
Great
Broooooooooooo
It worked 🙏
🙏🙏🙏
I'm so excited and happy, thank you for the support
I also learned how to use if
And how to execute such a thing (send the message) if only a specific block is placed on the ground
should it not be leftover && spawnItem instead of item && spawnItem?
uh, nvm
Is it possible to to make nametag only mandatory when my:parameters is set? js event.customCommandRegistry.registerEnum("my:parameters", ["set", "reset"]) event.customCommandRegistry.registerCommand( { name: "my:command", description: "desc", permissionLevel: Minecraft.CommandPermissionLevel.Admin, cheatsRequired: false, mandatoryParameters: [ { name: "nametag:parameters", type: Minecraft.CustomCommandParamType.Enum }, { name: "player", type: Minecraft.CustomCommandParamType.EntitySelector }. { name: "nametag", type: Minecraft.CustomCommandParamType.String } ] },
probably not
sadge
you'll get an error if my:parameters is not registered and you used it
and also you can't change params dynamically
you can make the nametag parameter optional, and check if nametag:paramaters is set and then you can make nametag manadory by just returning a command result with failure in the status if it isn't provided.
but that won't bypass this:
OH
i understand now lol
yeah do this
no problem
huh, after years of brain----, i got it to work. (except for the recipe part 😢 ). i can't anymore.
w
but it's JSON UI + action form.. right?
ye
also it seems your music was recorded while recording the vid
oh sry lol
it's okay lol
you really need to remove the animation for the form to appear
anyway action form buttons are still buttons and can't really have "holding" like normal slots which is very problematic on mobile devices lol
you can't, atleast i don't think so
i myself have been looking for a bit.. but my searching was not fruitful.
about animation, you know something?
nah lol
gotta ask in #1067869374410657962
if you find out how to remove it, it'd be helpful if you ping me about the solution
as i also need it very much
sure thng
well have a great afternoon then.
?
oh. that's sad, good luck with your studies lol
hope so
@chilly fractal found a fix but it makes it look kinda laggy tho.
ooh
still want that?
uh, in the server form add this.
{
"namespace": "server_form",
"[email protected]_screen": {
"$screen_content": "server_form.main_screen_content",
"$screen_animations": [],
"button_mappings": [
{
"from_button_id": "button.menu_cancel",
"to_button_id": "button.menu_exit",
"mapping_type": "global"
}
]
}
// ..........
}
this would clear all the animation it had
thanks!
np
@chilly fractal imo, this one doesn't look that bad.
"namespace": "server_form",
"[email protected]_screen": {
"$screen_content": "server_form.main_screen_content",
"$screen_animations": [],
"$background_animations": []
},
there are flickers, but thats almost instantaneous
of course
and thank you to every single one who has helped you and every single one of us in our journeys
yup
@warm mason does this work now? ur opinion?
ima keep lookin ig
it's pretty good
like very actually
but it's not "fluent".. like.. state of form to next state.
its better, agreed, maybe i'll find best, who knows?
this is very great for most forms
this is great for something like a chess board or a phone UI, etc. something that needs to not flicker at all
hmm
yea it looks a bit weird but the form itself doesn't flicker. combined with movement disabling/enabling it would be 90% great for them.
currently an inventory seer, i am trying to give it a way to put items in the inventory
the taking logic works, but putting logic? i am still testing and pondering
good luck. these things can be frustrating
fr
like real real frustrating
so real
good luck.
it took me over a week for that table alone
thanx
umm, sending a scriptevent via scripts is possible but not stable?
for now, ill just use runCommand('scriptevent <eventId>')
Yeah.
system.sendScriptevent("id", "message") added in @minecraft/server 1.18.0
Documentation for @minecraft/server
oh, good then.
what you using it for?
activating my hydration addon functionality,
the function is inside another addon, so i need to send a scriptevent to run the function when both addons are activated
basically:
xCore has all addons functionality
xHydration wont work without it, so u have to activate both addons
do you care much for using libraries?
and in the xHydration script, i can detect if the xCore addon is activated or not to trigger the addon functionality
what is that?
like sharing dynamic properties?
no, it uses scriptevents
you can setup something to sync dynamic properties if you want though
anyways the current method i am using are good, i can use it to detect if my addons are activated or not, and it can detect when the world is fully loaded
You have 2 add-ons and want to check if they're both activated at the same time? (or it's just one-side relation)
Why doesn't it work?
stop using ai
all the stuff in there except for worldLoad and world.getPlayers() is incorrect
feels like this is more of using outdated stuff
rather than ai
world.events.tick was never a thing
change it tojs system.runInterval(() => { //code })
https://jaylydev.github.io/scriptapi-docs/latest/index.html
you can use this doc
do you not want to specify an interval?
for checking stuff
or does it default to 1
you dont need to
its 1 by default
oh interesting, i didn't actually know that
0 also does the same since its clamped
i havent used runTimeout for a long time so i forgir
its always 1 tick late execution
minimum
within the millisec, it's possible to clearRun it
interesting
Why does this happen? I don't understand much about blocks
My code is this:
world.beforeEvents.playerBreakBlock.subscribe((data) => {
const { block, itemStack, player } = data;
data.cancel = true
const item = new ItemStack("minecraft:apple", 1);
block.dimension.spawnItem(item, block.location);
});
before events are "read only", meaning you cannot call apis that modify the world's state
you need to wrap that stuff in system.run(() => { /* code here */ })
some functions can be ran in read-only mode
which doesn't happen instantly
Oh okay, I get it, thnk
the core addon will detect my activated addons, the system is already finished, it works pretty well
How do i reverse an view vector, so it faces the opposite direction?
should just be able to multiply by -1 to flip it
Basically it should look in an different direction
Like if its
it should be <<
Sure?
yeah but remember you cant do object * number
so you'll have do something like this{x: vector.x * -1, y: vector.y * -1, z: vector.z * -1}
I see,hmm
Sure that would reverse the direction only?
Im using this for some kind of shield to detect if the projectile hits within 10deg of where the player looks
did you write that yourself?😭
it should.
it just makes negative positive, and positive negative.
therefore reverts it
im betting ai.
But it doesnt change the rotation only direction
I dont understand.
I just combined my knowledge in commands like what I knew about scripting and some things I was seeing on the website that was recommended to me
uh huh
makes sense, I feel like chatgpt could write it correctly tho💀
I see
Difficult to explain
Ill make a drawing later
you are talking about rotation, so is this a vector 2?
Im not sure
You can declare an item in both of these packs and then check if you can create an instance of a pack.
try {
new ItemStack("some:item_that_does_not_exist", 1)
} catch {
// this code will be executed if item does not exist
}
Hold on, yes
it wont work for addons that doesnt have custom items, like AppleSkin
theres an AppleSkin addon?
ur idea will work tho
cool
it will recieve a big update soon
enhancing the ui system, removing the delays, making it compatible with my hydration addon
Yellow projectiles should return false and red true the blue circle is where the black view vector comes from
it will works on custom food items too, like it shows u the custom food info when u hold it
shameless plug
lmao
im doing a thirst system too
its pretty simple, just some dynamic properties
yup
like one or two
and im using the new exhaustion api
It was. Back in 1.1.0-beta for 1.19.50, then 1.19.60. They removed it in 1.19.70 for 1.1.0-beta when they introduced system.run(), etc.
oh so u are detecting when the player exhaustion reaches 4 to decrease the thirs?
3 actually, so it depletes faster than hunger
Oh that's interesting, my scripting knowledge doesn't go that far back
Was there no concept of before/after events either?
that works but, sometimes the script wont be fast enough to detect the exhaustion value
seems fine to me.
are you running it every tick?
yes,
I didnt have issues
if u have hunger effect, it wont catch it sometimes
hm
like hunger 2+ will make it buggy
noted
do some testing ig
there was, but not that specific. (Ie there’s beforeChat and chat event, but there isn’t a beforeTick event when there’s a tick event)
thanks for the heads up
There was but it was written differently.
world.events.beforeChatEvents.subscribe()
Versus
world.beforeEvents.chatSend.subscribe()
Going off memory.
u can detext when the player loses a saturation/hunger point instead, it wont have any issues at all
even with hunger 255
yeah but then what if the player keeps eating
they wont drain thirst normally
I mean like, it wont be detached
it will detect the saturation, u cant eat to restore saturation when the hunger is full
is this practical? for my kits, I gotta register all the items so I can set up players inventories/equipment, this is js a bunch of export const of itemStacks
like 300 lines
with some foods you can tho
like an apple
u can recreate the exhaustion system
thats what I did before
but gl detecting when the player jumps
so I guess, using my old system would be better
u cant detect when the player jumps, like playerJump.afterEvent
you can
show me how, and i will show u how buggy it is
-# ill be back in 4m
Documentation for @minecraft/server
yeah exactly, it wont detect when the player jumps
like PlayerJumpAfterEvent
it does
the system is not perfect tho
like I said i didnt use that
u can detect when the player is jumping, but not when the player jumps, idk i cant explain it
you can though...
in order to understand what i mean, console.warn the player exhaustion, and just keep jumping
I know what the exhaustion does
see how will the exhaustion value will go up each time u jump, also try jumping under a block, like spam jumping
see how will the value keep increasing like crazy
u cant really do that in scripts
i tried everything
welp the game is written that way, just input for jumping
what 😭
lol
u better make ur thirst system slow, bec u cant get access to pure water early on
also, show me the hydration system on ur addon, like how to get hydrated
its not finished, so no
mhm

?
hmmm
mhm what
<villager-noise>
it'll be as fast as the host configures it
and you'll get water "saturation" when you first spawn.
just like hunger
anyways, gl making a temperature system after this thirst addon
if u made a thirst addon, everyone will ask for a temperature addon, so gl dealing with the system
idk i found it a little too complicated
SHOW ME
theres a getBiome method in preview
^
hmm
what about armor?
blocks like staying in water?
thats like 100 lines MAX for everything else
just detect it.
my temperature addon will have two new armor sets, leaf armor and goat-fur armor
each one has some downsides
yeah and then you lose armor values
or make a object array like "minecraft:chain_helmet": { temperature_increase: 3 },
then add it all up and set it
i have no idea how array works tho
well obv
i never deal with them
...
works like this
thats not an array
same thing
yapa yapa
Obj are faster
idek if i hazve a single array
so you do know the difference
time to script
the issue is, my armor system has different values in different biomes,
then make that
so i dont think the array will works fine for me
it does
I would add a value for everything else that doesn't match anything so other add-ons armour increase it a bit too
this is what i mean
Leaf Armor:
- Cold: 1 - (0.2 + 0.3 + 0.25 + 0.2) = 0.05 → -95%
- Hot: 1 - (0.15 + 0.25 + 0.2 + 0.15) = 0.25 → -75%
- Chilly/Mild: 1 - (0.1 + 0.2 + 0.15 + 0.1) = 0.45 → -55%
eh
it has different values in different biomes
Eh indeed
const armorData = [
{
armor: "Leaf Armor",
effects: [
{
condition: "Cold",
calculation: "1 - (0.2 + 0.3 + 0.25 + 0.2) = 0.05",
result: "-95%"
},
{
condition: "Hot",
calculation: "1 - (0.15 + 0.25 + 0.2 + 0.15) = 0.25",
result: "-75%"
},
{
condition: "Chilly/Warm",
calculation: "1 - (0.1 + 0.2 + 0.15 + 0.1) = 0.45",
result: "-55%"
}
]
}
];
chatgpt moment
yay more ai
Does afterEvents.playerPlaceBlock not have itemStack?
its after so no it would just be air if it did or the same block if its a stack
no
yeah
you edited your message
You could just make a multiplier for each biome
The armors have a value but before calculating how that affects the player temperature you multiply it by the biome temperature multiplier
i forgor to add the last part
hm
So how can I detect the item that was in the player's hand after I placed a block?
get the equippable component
run a function on beforeplace
then run it a tick late o smt
or*
thats what i did
ig
Documentation for @minecraft/server
nope, i have my own system for that
Nope
You hard coded the values
Hm, I'm not that good with scripts, but I'll try to do this
HelmetBonus / HelmetEnchantBonus + ChestplateBonus / ChestplateEnchantBonus + LeggingsBonus / LeggingsEnchantBonus + BootsBonus / BootsEnchantBonus
each armor will have different value if it has fire protection enchant
Again, multiplier
function getItemAfterPlace(player) {
system.runTimeout(() => {
//ur code here
}, 2)
}
just run function using before event
player?.setDynamicProperty('coldConditionMultiplier', eConditionMultiplierValue + ArmorBonus);
it works somewhere good ig
I know it work, just saying there is better way to do things
all i have to do next is increasing the temperature value from being too small, like 0,025
Like this?
function getItemAfterPlace(player) {
system.runTimeout(() => {
const inv = player.getComponent("inventory").container;
const hand = inv?.getItem(player.selectedSlotIndex);
const item = hand.typeId == "minecraft:hopper";
if (item && item.nameTag?.includes("Tier")) {
player.sendMessage("success");
}
}, 2)
}
looks right to me
just remember to import system
Ok
This is appearing:
[Scripting][error]-TypeError: cannot read property 'subscribe' of undefined at <anonymous> (index.js:103)
[Scripting][error]-Plugin [Addon - [index.js] ran with error: [TypeError: cannot read property 'subscribe' of undefined at <anonymous> (index.js:103)
]
then its ur event
I think it's something related to "beforeEvents.playerPlaceBlock"
have you enabled beta apis? some before events are beta only
Oh, right, I forgot about that
I didn't want to use beta apis, but it's the only way
you didnt need to create a function
Is it not possible to have custom discs with custom songs? They have to replace existing disc sound files? https://learn.microsoft.com/en-us/minecraft/creator/reference/content/itemreference/examples/itemcomponents/minecraft_record?view=minecraft-bedrock-stable
Wrong channel, but correct.
You can check #1072983602821861426 for workarounds.
Oh oops thanks!
Is it possible to detect if an entity is an adult?
if (entity.getComponent('is_baby') == undefined) {
}
what about hasComponent
Dont be rude @warm mason
!entity.hasComponent('is_baby') would work too yeah
is there a smoother way to move an entity other than running a entity.applyImpulse... every tick?
gametest
Is it possible to create a UI that only appears if there is a specific tag on the player, and it changes according to the value of a scoreboard?
what do you mean?
cant u tp gradually
yeah but i think thatll be more jolty
You could applyKnockback every tick, lol
Action form ui or json UI?
I don't know the difference between the two, can you explain it to me?
When I said action form I was referring to general scripting UI but to simplify it as much as possible Action Forms, Message Forms and Modal Forms are all scripting ui and looks like the picture below
Whereas, json ui is more like the in game vanilla ui, as in crafting table, inventory, so on and so forth
I understand, but it's not that type, but something like an image.
I intended to add a bar like the one in the image above
Where it is controlled according to the value of a specific scoreboard
Is there a reason that I shouldn't use world.setDynamicProperty() for like a couple hundred to maybe thousands of key value pairs?
dynamic properties feel super powerful, surely there is a downside to doing this
Maybe run some tests were you add long dynamic properties to the world
I feel like u could get away with a few hundred sense it's usually static data
But maybe you'll feel some lag if there all dynamically changing every tick
They would only be strings of a couple characters long (20ish max)
Dynamic or static?
Yea I feel like you could get away with upwards of 250, but I've never try anything like it so I'm not sure
Yea, maybe write a function that adds 50 character keys and values ever half second and see how long it takes before u feel lag or something
how would I tell if its lagging the game? since they aren't being called very often, just kind of existing in large quantities
Good point, I'm not sure how often the data is being referenced
I mean I was able to store multiple inventories on player, and that's like 500 character per saved inventory
Oh you could check would size every minute or so
So js log out and see how much of difference it makes
One message removed from a suspended account.
I've got a unique dynamic property being created every tick with 50 character string. we'll see what happens lol
what are you expecting and what is happening?
One message removed from a suspended account.
One message removed from a suspended account.
Nice lol
One message removed from a suspended account.
Maybe health is check per half, try 20
One message removed from a suspended account.
One message removed from a suspended account.
try using console.log(currenthealth) and make sure its what you expect it to be
One message removed from a suspended account.
One message removed from a suspended account.
Quick update:
10k properties in and doesn't seem to be any issues. although it doesn't like when you call world.getDynamicPropertyIds()
Is it possible?
That's understandable, has the world size increased much?
0.3 MB because I messed up the property and the string is only like 10 characters long
Wow, that's impressive still, I thought it would be more, maybe try looping though each one and sending a message
now how does one delete roughly 10k dynamic properties from your world. not that I have that many... 🙃
that doesn't seem to bother it either. at least not at once per tick
Intresstinnggg
Loop through em all and set them to undefined or null I think
I wonder what information makes the properties dense
[Scripting][error]-TypeError: cannot read property 'subscribe' of undefined at <anonymous> (enchMomentum.js:118)
This is line 118: world.beforeEvents.chatSend.subscribe((ev) => {
Why?
Are you using beta api? chatSend event isn't stable.
you need beta api for it
Ohh thanks
With "onPlayerInteract" on the block, can't the event be canceled?
No, it can't be. Use PlayerInteractWithBlockBeforeEvent instead.
Well, in fact, you can block this event via PlayerInteractWithBlockBeforeEvent too
I'm using it to create the system for the slabs, but I have a problem: I don't understand why the custom slab only interacts with the custom slab. The swing appears, but if I have a custom slab and interact with a block next to it, the swing doesn’t start, even though the event does
Is it possible to have rawtext as command parameter?
Just do a string and parse it as json
for someone who just codes in one file, modularity at this level is such an achievement.
Doing more and more projects is the best way to learn structuring
Its ok yeah, theres definitely still improvements to be made
like
Its all personal preference, but you could move the individual registry files into their folders, so the menu folder includes the menu registry code + all the menus
good idea
Also for the future you should make utils a folder
yup, and?
Thats good for now
Would be even better if I could see the code, structure is really dependant on the code. Most other suggestions I would give are just very personal preference, but what you have is definetly not bad. Most important is that your comfortable with your code base
thats right. should i send the code over to you, perhaps?
Nono
We can one day hop into a vc, but that will turn into a full on code review
im quite uncomfortable in vc
introvert kinda things
sure if its just screen sharing.
btw thanks.
Np, I like it when people actually care about code quality
its only recent awareness tho.
i was a guy whose motto was "make it work"
how? dont care.
Yeah like 99% of the bedrock community
Sometimes its good to have that mindset, but if you actually want to improve, you should care
And one day you will just write decent quality code without thinking about it
you must hate me then
jk
I use to have structre, but I had to edit tons of stuff, and everything got complied into one folder so I just left it🥀
I don't hate anyone, if your ever work with me, you will see that I would just give tips and tricks and help the other get onto a level, where we can work together comfortably. Sadly it doesn't always work out, bcs of time constrains
oh, yea I meant that as a joke XD.
anyways, make sure to show me the results,
- will it be compatible with custom food/drinks? for my addon it is, it just requires a specific tag
i'll show it off when I think its in a good place.
Stupid question:
when you have a script that check when a block is broken, placed, interacted with etc.
Does this script only check the block that has that script as part of its custom component, or will it check every block in the world and then check if its the applicable block before doing the rest of whatever the script is about?
Because if yes, wouldn't that make the code a bit clunky or demanding in performance when stacked up with multiple blocks and/or addons?
And wouldn't there be a way for the script to fire only when the relevant block it is supposed to run with be triggered for its event?
ex. interacting with custom block A triggers event B. Instead of interacting with every block in general (or just interacting as an action) for the script to constantly check for custom block A to trigger event B.
the game register the callback only for blocks that have custom components
assuming you are talking about custom components events
ItemFoodComponent
only work for apples?
and some other foods I think, but yeah, not all vanilla foods have the component.
it's annoying
@civic nest
🤷♂️
when it comes to vanilla foods just rely on the wiki for that info
i guess that's one way of doing it
what would you do
just create an object listing every vanilla food item and for each item have an object listing their food info.
and just go to the wiki for that data
custom components, yes
Mainly for blocks.
I have trouble understanding why the script I was learning was apparantly reading all interactions and then the script checks if it is the applicable block. And if there were something that makes the script trigger only when the block in question is interacted with, ticks or does an event in general.
In other words.
Would scripts run when the player does an interaction event. Which can be anything and thus unnecessary for everything other than the block that the script is supposed to trigger on.
Or would interacting with the only the applicable block make the script run.
The former makes the script run several times and make unnecessary checks, while the latter only checks for when the block in question is doing an event.
that doesn't sound like custom components
hmm?
the itemFoodComponent properties
I was thinking of only doing the info the food component provides.
and use the wiki to help figure that out
yeah, there was a lot tho. typing all that will be a nightmare
that just the raw stuff i got from it
it'll just be tedious
yeah
also you typing all that stuff out would take as long as you gathering the data from the wiki...
not as long but both seem tedious to me.
not really, i used ai
Ai prompt:
I have this link and there is a table in it formatted like this
"x"
scrap that data and follow the link to the item page, in it there is this table
"y"
use both of those and put the data into a json file formatted like this
"z"
i guess
you saying that made me think you did.
dont blame you using ai for that though, wouldnt want to sit there doing that.
no i didn't
i mean i know how to use axios and most scraping tools but i am not making a code that i only run once and delete it
i made this after all
https://github.com/MinecraftBedrockArabic/Modbay-Feed-Discord-bot
i don't want to go through that again, lol
Wazzup guys
Sup
cody where do you get these sick pfp's 😭
send me some in dm
The /toggledownfall command doesn't trigger the WeatherChangeAfterEvent, bug or no?
...what?
toggledownfall??
if it doesn't, maybe you can make a bug report.
if I remember correctly, the weather command also does not trigger it
/weather triggers the event
Hey @fiery solar, I was wondering on your "Quantum Entities" post, how did you detect whether the player is looking at the entity?
Is it scripts or the same thing creaking uses?
If scripts, can you please share how?
function isLookingAtEntity(player, maxDistance) {
try {
const rayEntity = player.getEntitiesFromViewDirection({ maxDistance: maxDistance })[0]?.entity;
if (rayEntity) {
return true;
}
} catch (e) { return false; }
}```
How does one blank out the off-hand slot?
I tried this:
equippableComponent.setEquipment(EquipmentSlot.Offhand, undefined);
Doesn't work.
do you get an error
I do not.
yeah, works with the other slots like head, chest, leggings, etc

ok... then it worked that time... I swear this game is off its rocker sometimes
hmmm
it's literally everywhere, it's just "Itzy Yeji"
maybe u have another code that sets ur offhand...
that works as inteded btw
Isn't that only entities that are on the player's cursor?
yeah
yeah I wasn't talking about that
well if you meant player's whole screen view thats also possible
How so?
maybe this way
^
import { Entity } from "@minecraft/server";
Entity.prototype.getEntitiesFromAngle = function (maxDistance = 6, fov = 60, options = {}) {
const viewDir = this.getViewDirection();
const pLoc = this.location;
const queryOptions = {
...options,
maxDistance,
location: pLoc
};
const cosFov = Math.cos((fov * Math.PI) / 180);
const results = [];
for (const entity of this.dimension.getEntities(queryOptions)) {
if (entity === this) continue;
const eLoc = entity.location;
const toEntity = {
x: eLoc.x - pLoc.x,
y: eLoc.y - pLoc.y,
z: eLoc.z - pLoc.z
};
const dot = viewDir.x * toEntity.x + viewDir.y * toEntity.y + viewDir.z * toEntity.z;
const mag = Math.sqrt(toEntity.x ** 2 + toEntity.y ** 2 + toEntity.z ** 2);
if (mag === 0) continue;
const cosAngle = dot / mag;
if (cosAngle >= cosFov) results.push(entity);
}
return results;
};
I would avoid assigning the maxDistance and location properties to the options parameter, as this mutates the object being passed in.
In most cases this shouldn't matter, since people are very likely to give it an object literal. But that is something to consider if someone passes a variable as an argument
yeah, you are are right
Instead, I would construct a new object in the getEntities call with the new properties passed in:
for (const entity of this.dimension.getEntities({...options, maxDistance, location: pLoc})) {
updated, thanks for pointing that out
I'm learning more about scripting. When I run /reload are all existing subscriptions automatically cleaned up or do I need to manually unsubscribe to the events I subscribed to?
Cleaned up.
how do I stop the player from dying and instead give a tag?
i think you cant really stop an entity's death without editing entity behavior

You have to reimplement health system from scratch to do this.
I tried to set min health to 1 then check if damage received was fatal but it seems min in health component was removed
Hello here, does anyone here encounter the same issue with me?
Whenever i add a new file or folder inside my script folder, i still need to re-open Minecraft instead of just reloading it. Before I just /reload and it will detect new file script added but now I need to re-open Minecraft just to detect new file.
i dont remember detecting new files with a reload
js can be detected even just reload, json needs to re open the world
to me it didnt work like that iirc, js json all needed reopening world
ig ive the same issue as you lol
for new folders it has to be re-opened last time I tried
I only have to relog for it to work
hm
When I constantly add dynamicProperty to my item, it keeps moving in my hand 😭
halp
it also makes it have "has custom properties" lore
thats not the problem but the problem is its moving like when you interact/consume something, i cant find a way to save itemstack as dynamicproperty in world or player
That's normal, you're replacing the item in hand constantly.
The "has custom properties" can be toggled with a gamerule /gamerule showtags false
Can I ask why you're constantly replacing the item?
Before you replace you can get the item alot number, and replace it with its alot number
Hi can some help me my friend do me a scoreboard script but he mean that I have too modify some things what I have too modify
import {
BlockExplodeAfterEvent,
BlockVolume,
Dimension,
ListBlockVolume,
Player,
PlayerBreakBlockBeforeEvent,
system,
UnloadedChunksError,
world,
type Vector3,
} from "@minecraft/server";
import { BlockPattern } from "BlockPattern";
import { getStringFromDynamicProperties } from "getStringFromDynamicProperties";
import { sellAllMaterialsForPlayer } from "materialSell";
import { numberFormatter_compact_lite } from "numberFormatter";
import { saveStringToDynamicProperties } from "saveStringToDynamicProperties";
/**
* Updates the sidebar for a player with their rank, money, and other information.
*
* @param {Player} player The player whose sidebar will be updated.
*/
export function updateSidebar(player: Player): void {
if (!player.isValid) return;
const rankTags: string[] = player.getTags().filter((tag) => tag.startsWith("rank:"));
const sidebarTitleText: string = `§a§n§d§e§x§n§o§v§a§_§s§i§d§e§b§a§r§_§t§i§t§l§e§r§dIGN: §r${player.name}§r
§gRank: §r${rankTags.length > 0 ? rankTags.map((tag) => tag.replace("rank:", "")).join(", ") : "§bMember"}§r
§aMoney: §r§2§a${playerMoneyData.get(player) !== undefined ? numberFormatter_compact_lite(playerMoneyData.get(player)!.toString(), true) : "§dLoading..."}§r
§vMine Rank: §r§b${player.getDynamicProperty("mineRank") ?? "§cNone"}§r`;
const sidebarSubtitleText: string = `§9Discord: §r§bheCTKamNWZ§r
§dRealm: §r§eA7GcoEgktxYHibk§r
§cIP: §r§e74.208.75.189§f:§e19132§r
§eTPS: §r${avgTps1SecondColor}${avgTPS1Second.toFixed(0)}§r`;
player.onScreenDisplay.setTitle(sidebarTitleText, { fadeInDuration: 0, stayDuration: 1200, fadeOutDuration: 0, subtitle: sidebarSubtitleText });
}
What do you want
Its a sidebar Scoreboard because I'm too stupid @winged gull have do it me but I dont know what I have too modify that I work
i am not replacing the item. Setting dynamic property on the itemStack constantly is causing this.
can you show your code?
Me?
I think I know what ur doing, do you save the current item before replacing?
finna
Oh :(. Than I get ignore
shhhh
bruh💀
Go back to the documentation
Idek its half AI lmao
What's the functionality
Its a flashlight script which places light blocks around and saves the battery charge percentage across each flashlight item, which i am using dynamicProperty for, to save the charge value.
Pls 🥹
Please stop begging.
Either learn basics of script api and have patience, Because you just pasted a whole chunk of code written by another person and asking for help repeatedly
If you set the item back it jumps in your hand. If you do not set it back it does not jump. I just tested it.
Maybe AI secretly put that in my code.... Yuh ill see tmr
Where you save the durability, save the item stack slot number, and save it where u save the durability
Sorry Im on not on pc 😓
It's ight
Definitely did lol
this is being said by a dude who said a few messages ago "Idek its half AI lmao"
🤷♂️
Almost certain that was made on chatGPT(won’t work)
And everything is wrong there.
Just the js syntax is ok, all the minecraft scripting logic is wrong there.
Bruh than my friend scams me??
?????
AI is useful "If you know what you're doing", I've trained my AI and about that person, He's just pasting a chunk of code he doesn't even know what it does..
Minecraft released 1.21.120 preview when 1.21.110 is not released. Next update will be 1.21.110 (2.3.0-beta) or 1.21.120 (2.4.0-beta)?
the next update will be 1.21.110
they always start the preview cycle of the next update before the previous one releases
is it possible to replicate runCommandAsync in @minecraft/[email protected]?
runJob
runCommand
marathonCommand
walkJob
marchCommand
system.beforeEvents.startup.subscribe((init) => {
const testCommand = {
name: "lu:test",
description: "test",
permissionLevel: 3,
cheatsRequired: true
}
init.customCommandRegistry.registerCommand(testCommand, test());
});
function test(player) {
let ply = Player_DB.get(player.id)
world.sendMessage(JSON.stringify(ply))
}
hey guy how to get the player who did the command
system.beforeEvents.startup.subscribe((init) => {
const testCommand = {
name: "lu:test",
description: "test",
permissionLevel: 3,
cheatsRequired: true
}
init.customCommandRegistry.registerCommand(testCommand, test);
});
function test(result) {
let ply = Player_DB.get(result.sourceEntity.id);
world.sendMessage(JSON.stringify(ply));
}
thank you
someone would like how an add arguments to a command?
always do ur research for things u dont/do know
How to add like numbers to a property instead of setting it? setProperty("example:property", 2)
Doing this but in scripts
"set_property": { "example:my_int": "query.property('example:my_int') + 1" }
const prop = getProperty("example:property")
setProperty("example:property", prop + 1)```
Old thread, but still a relevant topic I think. I recently asked chatgpt to refactor some minified Javascript and it got the logic wrong several times. Most of the time it was correct, but it was so time consuming carefully checking each line. Or it would just leave out parts. I've started just refactoring it myself.
So many little glitches with AI, and so unsatisfying carefully checking it compared to me just rewriting it. I experimented with asking it to refactor Boolean statements and it still got it wrong sometimes. When I restated the same Boolean statements but with simple a, b, c instead of longer variable representations, it would sometimes tell me the opposite logic result.
When a computer program gets logic wrong, you know you're not dealing with something deterministic and reliable. A program to refactor code deterministically (traditional coding) would be far more reliable here - I'm sure some exist.
What I have found AI useful for is identifying coding patterns from very little code given to it that I'm unclear about the function of, because pattern recognition is about the most useful application of machine learning.
And sometimes explaining stuff and answering questions but even then it can lead me up the garden path because it doesn't really understand context.
Hello creators, can I summon a warden where the custom projectile will hit, but only owner player can lauch the projectile not other players
Owner player mean, player who will spawn the projectile
Is it possible?
cancel item use ?
?
It's your question or related to my question?
your
