#Script API General
1 messages Β· Page 33 of 1
is there a error in the game?
Again, did you update your types?
I haven't tested
then you have problems with the code editor. This is not for me
Hey does someone have a force show function?
server-ui may be overriding your server module with the stable version and not actually enforcing the beta version you are requesting. This is because the server-ui has a dependency for the stable version and it causes conflicts. I personally work around this issue doing the following:
"dependencies": {
"@minecraft/server-ui": "1.4.0-beta.1.21.44-stable",
"@minecraft/server": "1.16.0-beta.1.21.44-stable"
},
"overrides": {
"@minecraft/server-ui": {
"@minecraft/server": "1.16.0-beta.1.21.44-stable"
}
}
Try this and execute npm i to see if that resolved it. You may or may not need to wipe out the node_modules folder too and repopulate it with the npm i command.
Anyone know how i can add to my chest ui that if i click a item i will get tped to like my arena with the kit equipped?
Do you have the Content Log enabled? In Settings β Creator (command block icon)
Pack imports usually don't throw errors to the log but it can. There may be more information there
Having the file on with GUI off isn't too helpful. Toggle those both
Once that's done, try importing your mcpack again
Thats sus
Do u wanna see my pack?
Maybe something there is wrong
Thats what i wanna test but i cant import it
Zip the contents of the folder, not the folder its self
Guys... Is destructing the cancel in the before events work now or still nah?
world.beforeEvents.chatSend.subscribe(({ message, sender, cancel }) => {
if (message === '!test') {
cancel = true;
sender.sendMessage('bruh');
}
});```
Yo it's Navi... Hi
it won't work if you dereference cancel
Still a no.
reminder for me to fix my bot
for what
dynamic properties
I'm using an item to make changes to an entity but the player won't necessarily be interacting with it.
How?
entity.setDynamicProperty('whatever', entity.id)
player.setDynamicProperty('whatever', entity.id)
world.setDynamicProperty('whatever', entity.id)
These save even if the player leave right?
yes
π
I wish getRotation() was a thing for players
it is
Wait it works on players?
O i was thinkin of setRotation
Lol
I just asked, cause I saw in someone's code that did destructure it directly instead of using a short name
They may not know.
world cant run command directly
you need to get dimension from players
(also playAnimation native function exists)
so do player.runCommandAsync
however I recommend using the native method to play animations
yes
What do you mean? I don't want to run the animation on the player. But on a mob, only if it has a specific tag.
what
Sorry
oh
youre basically running the command from players
Just get the entity with that tag or typeid and do the animations
you can just get all entities and do playAnimation on the entities
Simple as that
no, it'll try to run the animation on the player
you need to get the entities in the world
Fr dude
const entity = world.getDimension('overworld').getEntities({ tags: [] });
entity?.playAnimation()```
I forgor how to define the typeid
that wont work.
you need to loop it, its an array
You still need to
that wouldnt be the same though
or just add [0]
a hell na
haha
I'm just joking c'mon
Idk I just use it simple things lol
const entity = world.getDimension('overworld').getEntities({ tags: ["madara.died"] });
entity.typeId=="n:madara".playAnimation("animation.madara.died")
its not about it being simple, its about what it does
const entity = world.getDimension('overworld').getEntities().find(entity => entity.typeId === '');
entity?.playAnimation()```
coddy you messed up
I usually just use it for this
:skull
oml
That's not my freaking fault πππ
hey, just refer to this link and scroll up, remove the despawn entity stuff
Btw this is I usually do @thorn flicker
it'll only grab 1 entity from the array.
me when js for
i cant believe i had to edit that
if thats what you want, cool
const query = {type"n:madara", tags:["died"]}
for (const e of getEntities(query)) {
//e.playAnimation()
//e.matches(query) && e.playAnimation()
}```
needs the dimension class.
Its just outline
if I was hash rn I would close discord
my system does not work when the entity is born
Sorry for the delay, my internet went out
But yeh, the dimensions has to be specified
not that
okay
hang tight, brb.
Nah, it gets everyone in my case... Idk I probably did use for const whatever
But yeah...
I messed up so badly guys
Sorry I fumbled not once but 4 time
for (const dimensions of ['overworld', 'the_end', 'the_nether']) {
for (const entity of world.getDimension(dimensions).getEntities({type: "namespace:entity"})) {
entity.playAnimation('animation')
}
}
also if you can, I recommend using animation controllers instead, more performant.
Has anymore encountered items in bundles sometimes disappearing when you move them between containers?
Here's a nicer version:
export namespace UUID {
const LUT: string[] = Array.from<string, string>({ length: 256 }, (_v, i) => {
return i.toString(16).padStart(2, '0')
})
/**
* Generates a random UUID (RFC4122 version 4 compliant).
* @returns {string} The generated UUID.
*/
export function generate(): string {
const r = (Math.random() * 0x100000000) >>> 0
const s = (Math.random() * 0x100000000) >>> 0
const t = (Math.random() * 0x100000000) >>> 0
const u = (Math.random() * 0x100000000) >>> 0
return [
LUT[r & 0xff],
LUT[(r >> 8) & 0xff],
LUT[(r >> 16) & 0xff],
LUT[(r >> 24) & 0xff],
'-',
LUT[s & 0xff],
LUT[(s >> 8) & 0xff],
'-',
LUT[((s >> 16) & 0x0f) | 0x40],
LUT[(s >> 24) & 0xff],
'-',
LUT[(t & 0x3f) | 0x80],
LUT[(t >> 8) & 0xff],
'-',
LUT[(t >> 16) & 0xff],
LUT[(t >> 24) & 0xff],
LUT[u & 0xff],
LUT[(u >> 8) & 0xff],
LUT[(u >> 16) & 0xff],
LUT[(u >> 24) & 0xff]
].join('')
}
/**
* Validates a given UUID string.
* @param {string} uuid - The string to validate as a UUID.
* @returns {boolean} - Returns true if the string is a valid UUID, false otherwise.
*/
export function isValid(uuid: string): boolean {
const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
return regex.test(uuid)
}
}
performance is a lil better cause you don't have to build the LUT every time
Bro you jumpscared me
Here's a much nicer version for Android users:
-# this is a joke
export namespace UUID {
const LUT: string[] = Array.from<string, string>({ length: 256 }, (_v, i) => {
return i.toString(16).padStart(2, '0')
})
/**
* Generates a random UUID (RFC4122 version 4 compliant).
* @returns {string} The generated UUID.
*/
export function generate(): string {
const r = (Math.random() * 0x100000000) >>> 0
const s = (Math.random() * 0x100000000) >>> 0
const t = (Math.random() * 0x100000000) >>> 0
const u = (Math.random() * 0x100000000) >>> 0
return [
LUT[r & 0xff],
LUT[(r >> 8) & 0xff],
LUT[(r >> 16) & 0xff],
LUT[(r >> 24) & 0xff],
'-',
LUT[s & 0xff],
LUT[(s >> 8) & 0xff],
'-',
LUT[((s >> 16) & 0x0f) | 0x40],
LUT[(s >> 24) & 0xff],
'-',
LUT[(t & 0x3f) | 0x80],
LUT[(t >> 8) & 0xff],
'-',
LUT[(t >> 16) & 0xff],
LUT[(t >> 24) & 0xff],
LUT[u & 0xff],
LUT[(u >> 8) & 0xff],
LUT[(u >> 16) & 0xff],
LUT[(u >> 24) & 0xff]
].join('')
}
/**
* Validates whether a given string is a valid UUID.
* @param {string} uuid - The string to validate as a UUID.
* @returns {boolean} - Returns true if the string is a valid UUID, false otherwise.
*/
export function isValid(uuid: string): boolean {
const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
return regex.test(uuid)
}
}
You just sended it randomly here especially since it's pure white not formatted
Yes it doesn't..
Only in desktop
Yea, I got another one too. Couldn't find it earlier, but it's faster than my previous one. I got a link that demonstrates the speed for this version, my previous response, and the other one I couldn't find until a little later.
yeah the array join is slightly slower than string concatenation, but a bit neater for readability
eh nevermind not really
they're similar readability lmao
jsut whatever you wanna use ig
I dont understand what u mean
guys, how can i increase the inventory size of my entity using scripts?
Bridge is broken again, i cant use getComponent
const inv = entity.getComponent('inventory').container;
inv.size ???
Inventory size is determined by their entity JSON
i want to increase the size of it using scripts if it possible, without editing the entity json

not possible
select everything inside the folder and then click compress to zip
You can't
ik
Guys, is before events of playerInteractWithEntity beta or nah now
stable
probably
has to be

Less go after a long long time of suffering finding an alternative of it before.
Wtf
yah it is stable now,
π§
Because I'm sure the player break block and place is already stable now
@dim tusk
stable
interacting with blocks or entities before and after events are stable now
Nice thanks, I'm pretty lazy to open the changelog
Yo is there a way to set the xp of the player?
Reset*
Like a method, instead of getting xp and adding -xp gotten
To reset.
To 0...
There is resetLevel but it doesn't reset xp
Yeah there probably isn't a way.
I'll just reset using some calculations
player.addExperience(-player.xpEarnedAtCurrentLevel)
import * as mc from "@minecraft/server";
mc.system.afterEvents.scriptEventReceive.subscribe(event => {
const wg = event.id.split("wg:")[1];
const player = event.sourceEntity;
switch (wg) {
case "plains":
biome(player, "plains");
break
}
});
function biome(player, biome) {
let biomeLocation = player.dimension.findClosestBiome(player.location, biome);
player.runCommand(`tellraw @s {"rawtext":[{"text":"Coords: ${biomeLocation}"}]}`);
}
help me
what's wrong?
shouldn't you split with ":"?
otherwise change the [1] to [0]
Brilliant
import * as mc from "@minecraft/server";
mc.system.afterEvents.scriptEventReceive.subscribe(event => {
const wg = event.id.split(":")[1];
const player = event.sourceEntity;
biome(player, wg)
});
function biome(player, biome) {
let biomeLocation = player.dimension.findClosestBiome(player.location, biome);
player.runCommand(`tellraw @s {"rawtext":[{"text":"Coords: ${biomeLocation}"}]}`);
}```
hmm not exactly, with the switch case it had protection for invalid biomes
just do a try catch, if the error means the biome is not valid
Had to make sure it won't throw errors xdd
bad practice ig
goofy ass coding
Or check for the presence of a biome in biome types
api 1.15.0?
no
oh yeah also you need a message for the scriptevent to send, eg /scriptevent wg:plains MESSAGE
you should instead check if the id is biome, and then use the message for the biome name
without the message it'll just not send at all
findClosestBiome in beta
afaik
oh no π¦
and now? π¦
the best scripts are always beta
Itβs just that when they come out of beta you already get used to them and consider them not the best
lol
I think the best ones are playerInteractWithBlock and itemUse events and system.runTimeout
Is there another way for me to find out the location of a biome?
no
/locate only works if you type it in chat, it doesn't work as a command in addons
it dose work
just no way of knowing the location it output
i guess it can be used to check if a structure/biome is present in a world
I put, "/locate biome plains" in a function, and when I activate it nothing happens
Found this.
// Script by WavePlayz
import { world, system, BlockTypes } from "@minecraft/server"; // Import necessary modules from the Minecraft server API
// Listen for the `chatSend` event, which is triggered when a player sends a message in chat
world.afterEvents.chatSend.subscribe(async (eventData) => {
// Destructure the `eventData` object to get the sender (player who sent the message) and the message itself
const { sender, message } = eventData;
// Check if the player sent the message "find biome"
if (message === "find biome") {
// Send a message to all players in the world, asking the player to close the chat
world.sendMessage("Close chat (2s)");
// Wait for 2 seconds (40 ticks) before continuing the script
await system.waitTicks(20 * 2);
// Define the biome ID to search for (in this case, "plains")
const biomeId = BlockTypes.get("plains").id;
// Define the dimensions of the bounding box (the area within which the search will be conducted)
const length = 100;
const height = 100;
const width = 100;
// Create a `BiomeSearchOptions` object with the defined bounding box dimensions
const biomeSearchOptions = {
boundingSize: { x: length, y: height, z: width },
};
// Use the player's current dimension to find the closest biome matching the specified `biomeId`
// The search will start from the player's current location and use the `biomeSearchOptions`
const biomeLocation = sender.dimension.findClosestBiome(
sender.location,
biomeId,
biomeSearchOptions
);
// Check if a biome was found
if (biomeLocation) {
// If found, send a message to the player with the coordinates of the biome
sender.sendMessage(
`Found biome '${biomeId}' at location: ${biomeLocation.x}, ${biomeLocation.y}, ${biomeLocation.z}`
);
} else {
// If not found, send a message to the player indicating that the biome was not found
sender.sendMessage(`Biome '${biomeId}' not found`);
}
}
});```
You cannot use beta functions
I said... I just found it.
const invo = entity.getComponent('inventory').container;
Is either the entity doesn't exist anymore or the entity doesn't have that component
Don't tell it's player
nvm, fixed
ignore me I'm braindead
can u help me detecting 3 extra slots in the player inventory?
i used this "minecraft:inventory": {"container_type": "container","can_be_siphoned_from": true,"inventory_size": 3} inside of the player.json and it did give the player 3 extra invisible slots, i wanna make sure i can detect those slots.
Tch tch tch
the extra slots are there, but how can i get access to them?
Yeah that's what I said ima do
You tried it?
via script?
i tried the normal way ( player.getComponent('inventory') ) and i cant detect the new extra slots
I'm trying to detect those extra slots via scripts, i wanna make sure its 100% impossible
Then minecraft doenst support new slots
There is no other way
i think by adding minecraft:inventory to the player.json will be open only by other players
just like normal entities, u can open it by interacting with the entity,
@slow walrus
Is there a onxpreceieve event or something?
Is input api in beta?
Are u guys talking with me
Why its not working, can some give me a good explain and help me with that please
Please i need that
Is it possible to spawn an item on the ground?
Yes.
How? spawnItem? Or something like that
Yep, Dimension.spawnItem.
Can anyone please help me with that
Is it possible to make a script to change the models and texture of the leaves before entering the Minecraft world?
is there a way to do item use without an item in the hand
No.
open a post and wait
-# personally i have no idea what is the problem. my fish brain can't follow what happening in the video
What's the error
mc.world.getDimension("overworld").spawnItem("minecraft:diamond", 1, entityLoc.x, entityLoc.y + 1, entityLoc.z)
Is this a site where u see these codes
import { ItemStack } from '@minecraft/server';
new ItemStack('minecraft:diamond', 1)```
ΛΛhΓ¬ΛΛ
How i can do that
EquipmentSlot { Chest } 'minecraft:diamond_chestplate'
what would that do
What is that π
that... wouldn't do anything
Idk π
I guess you want to equip a chestplate to the player
Im new and im trying to equip body with armor stuff with a code
Yess
const equippable = player.getComponent('equippable');
equippable.setEquipment('Chest', new ItemStack('diamond_chestplate'));
And if i want Helmet just
const equippable = player.getComponent('equippable');
equippable.setEquipment('Head', new ItemStack('diamond_chestplate'));
I think its obvious but you have to get the player in some way first
Yes
Nah u are the best man
Remember changing what piece of armor you are setting
Yes
const equippable = player.getComponent('equippable');
equippable.setEquipment('Head', new ItemStack('diamond_helmet'));
Guys, do you think you can recreate block blasts in mc?
Wait.. u don't know that game?
I'll try doing it. I just need to know the list of shapes lmao
import * as mc from "@minecraft/server";
mc.system.afterEvents.scriptEventReceive.subscribe(event => {
const wg = event.id.split(":")[1];
const player = event.sourceEntity;
biome(player, wg)
});
function biome(player, biome) {
let biomeLocation = player.dimension.findClosestBiome(player.location, biome);
player.runCommand(`tellraw @s {"rawtext":[{"text":"Coords: ${biomeLocation}"}]}`);
}
appears is "object Object" lol
JSON.stringify() it
what?
That's because it returns a Vector3.
You'll need to JSON.stringify(biomeLocation) or do biomeLocation.x
system.runInterval(() => {
["minecraft:overworld", "minecraft:nether", "minecraft:the_end"].forEach((dimension) => {
for (let entity of world.getDimension(dimension).getEntities({ type: "addon:jane" })) {
const ridingComp = entity.getComponent("riding");
const ridingPig = ridingComp?.entityRidingOn?.typeId === "minecraft:pig";
const ridingHorse = ridingComp?.entityRidingOn?.typeId === "minecraft:horse";
entity.setProperty("addon:riding", ridingPig ? 1 : ridingHorse ? 2 : 0);
entity.setProperty("addon:sheared", entity?.hasComponent("minecraft:is_sheared") ? 1 : 0);
const equip = entity.getComponent('equippable');
const main = equip.getEquipmentSlot('Mainhand');
console.error(main?.typeId ?? 'minecraft:air');
}
});
}, 5);```
How do I fix the error that `equip.getEquipmentSlot` causes?
Equippable can only work for players.
Oh....
Can I use equip_item instead?
What are you trying to do?
use getEquipment
This.
import { world, system } from "@minecraft/server";
system.runInterval(() => {
["minecraft:overworld", "minecraft:nether", "minecraft:the_end"].forEach((dimension) => {
for (let entity of world.getDimension(dimension).getEntities({ type: "addon:jane" })) {
const ridingComp = entity.getComponent("riding");
const ridingPig = ridingComp?.entityRidingOn?.typeId === "minecraft:pig";
const ridingHorse = ridingComp?.entityRidingOn?.typeId === "minecraft:horse";
entity.setProperty("addon:riding", ridingPig ? 1 : ridingHorse ? 2 : 0);
entity.setProperty("addon:sheared", entity?.hasComponent("is_sheared") ? 1 : 0);
const equip = entity.getComponent("equippable");
const main = equip?.getEquipmentSlot("Mainhand");
if (main && ["minecraft:bowl", "minecraft:poisonous_potato", "minecraft:spider_eye"].includes(main.typeId)) {
entity.dimension.playSound("jane.mob.reject", entity.location, { volume: 0.6, pitch: 0.8 });
entity.dimension.spawnItem(main, entity.location);
entity.runCommand("replaceitem entity @s slot.weapon.mainhand 0 air");
entity.runCommand("say test");
} else if (main?.typeId === "minecraft:cake") {
entity.triggerEvent("minecraft:become_witch");
entity.dimension.playSound("jane.mob.reject", entity.location, { volume: 0.6, pitch: 0.8 });
entity.runCommand("replaceitem entity @s slot.weapon.mainhand 0 air");
entity.runCommand("say test2");
}
}
});
}, 5);```
This one. But this didn't work so I reverted back to zero.
ContainerSlot needs to have slot.hasItem() for checking
@dim tusk
Does anyone know how I can make a menu with information appear when I enter the world?
//import from the menu module if you are going to use the Hit event put it here
import {ActionFormData} from '@minecraft/server-ui'
//event you want to put for example
//world.afterEvents.itemUse.subscribe
Function miMenu(player){
const mimenu = New ActionFormData();
mimenu.title('Β§lΒ§6WELCOME!'
mimenu.body('text hello how are you all')
mimenu.show(player)
}//Call the function with a return miMenu(player)
How can I do it?
I want a menu to appear when I enter the world, a welcome menu
Yea?
import { world } from "@minecraft/server";
import { MessageFormData } from "@minecraft/server-ui";
// Subscribe to player spawn event
world.afterEvents.playerSpawn.subscribe((event) => {
// Function to greet the player
function greetPlayer(player) {
const greetGUI = new MessageFormData();
// Set title and body for the greeting message
greetGUI.title("Β§lΒ§6WELCOME!"); // Title
greetGUI.body("Hello, how are you? Welcome to the server!"); // Body text
// Define two buttons
greetGUI.button1("Thank You!"); // Button 1: Acknowledge
greetGUI.button2("Exit"); // Button 2: Exit
// Show the form to the player and handle their selection
greetGUI.show(player)
.then((result) => {
// If the form was canceled due to "UserBusy", recall the function
if (result && result.canceled && result.cancelationReason === "UserBusy") {
greetPlayer(player); // Recall the function to show the message again
return; // Exit the current flow
}
// Handle button selections
if (result.selection === 0) {
// Acknowledge message
player.sendMessage("Thank you for joining! Have fun!");
} else if (result.selection === 1) {
// Kick the player if they select Exit
world.getDimension(player.dimension.id).runCommand(`kick ${player.name} Β§oΒ§7\n\nYou have selected to exit.`);
}
})
.catch((error) => {
// Log any errors that occur
console.error("Error showing greeting: ", error);
});
}
// Call the greeting function for the player
greetPlayer(event.player);
});
You can.. just use message from data right?
-# nevermind I read it as action form data lol
It was an earlier moment when I wanted the scripts with the run commands to work lol, nevermind that.
@remote oyster I just import it and that's it?
oh it worked for me! thanks so much!!
β€οΈ
How do I use the script debugger bot?
been awhile since i touch block permutation, when you set it's permutation every tick, does it make you unable to break it or place anything besides i?
how do i use simulated players?
-# never used them in my life lmao
import * as gameTest from '@minecraft/server-gametest';
gameTest
.register('StarterTests', 'playerTest', (test: gameTest.Test) => {
const player = test.spawnSimulatedPlayer({ x: 5, y: 2, z: 5 });
})
.maxTicks(400)
.structureName('gametests:mediumglass');
is this a help for me or you have a problem?
that's how you spawn a simulated player
Guys, do you think we can recreate the hole filler of mc java to bedrock?
I mean obviously you could...
-# I suck at math people
Search a 5x5 area around the hole & if it's air and the same level as the outer ring or same level as inner ring set the block and what's above it to whatever block.
It's gonna require some logic
@honest spear uhhh sorry for the ping, really really sorry, but your database has some error when I try to load an item
If we can move to dms it'd be appreciated too.
Are you on preview?
Nope, stable minecraft, 1.21.43
What kind of item you mean
And last question is if you try to use it in new world ?
A normal item, just I have an inventory saver system, I get the Player's Inventory, if it's not undefined it gets saved in the database.
?
You mean the database?
Or the item?
It throws an error if it has enchantments
Also it seems you don't clone the item using .clone() right?
Looks like the default serializer for enchantments is outdated
Cuz I tested also with a shulker with items and it got reset.
Yea
Now it's EnchantmentType
For the type
i wouldn't recommend saving items with serializers as they can't save all
Yeah ik
use entity inventories
Alright then. Been nice talking to ya!
i wish i could help more but serializers are mean to be for custom data types and API are not the best practice
It's okay, I'll work something out.
import * as mc from "@minecraft/server";
mc.system.afterEvents.scriptEventReceive.subscribe(event => {
const wg = event.id.split(":")[1];
const player = event.sourceEntity;
switch (wg) {
case 'plains':
biome(player, "plains");
break
}
});
function biome(player, biome) {
let biomeLocation = player.dimension.findClosestBiome(player.location, biome);
player.runCommand(`tellraw @s {"rawtext":[{"text":"Coords: ${JSON.stringify(biomeLocation)}"}]}`);
}
[Scripting][error]-CommandError: Syntax error: "z": unexpected in "Coords: {"Β»zΒ«":-5,"y":-"
at biome (biome.js:15)
at <anonymous> (biome.js:8)
help
You're not using beta
By the way, I donβt recommend naming variables and functions the same
Better yet, use API methods rather than commands
and that's why you have an error. stringify returned an object in the form {"propertyName": "propertyValue"} and in this object there is ", and they break the json structure in the tellraw command
function biome(player, biome) {
let biomeLocation = player.dimension.findClosestBiome(player.location, biome);
player.sendMessage("Coords: " + JSON.stringify(biomeLocation));
}
Thanks!
Are we not able to use a translation text from the lang file?
import * as mc from '@minecraft/server';
mc.system.runInterval(() => {
for (const player of mc.world.getPlayers()) {
for (const entity of mc.world.getDimension("overworld").getEntities({excludeFamilies:["inanimate"],excludeTypes:["item","xp_orb"]})) {
entity.nameTag = `${entity.typeId.replace('_', '').split(":")[1]}`;
}
}
}, 5);
?
Because you are replacing it with nothing, but it should be with an empty string
.replace('_', '')
Ohhh ok
yes?
?
does anyone know how I could format a date object? like instead of telling the player : "you have been banned until (date)" it says "you have been banned for "24d, 4h, 2m"
One of many possibilities
import { world } from "@minecraft/server";
// Assuming `banEndTime` is a timestamp in milliseconds when the ban ends
function getBanDuration(banEndTime) {
const currentTime = Date.now();
const timeDifference = banEndTime - currentTime;
// Calculate days, hours, and minutes
const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
// Format the duration
return `${days}d, ${hours}h, ${minutes}m`;
}
// Example usage
const banEndTime = Date.now() + (24 * 24 * 60 * 60 * 1000) + (4 * 60 * 60 * 1000) + (2 * 60 * 1000); // 24 days, 4 hours, 2 minutes from now
const banDuration = getBanDuration(banEndTime);
world.sendMessage(`You have been banned for ${banDuration}`);
Thank you
how do i get all of the players within 3 blocks of an entity
let players = entity.dimension.getPlayers({
maxDistance: 3,
location: entity.location
})
dimension.getEntities + EntityQueryOption
getPlayers better
I was blind when looking at the docs
ah, whats the difference between itemStackAfterBreak and itemStackBeforeBreak inside of the playerBreakBlock component?
some stuff can change between the tow states
item durability or the item break or change to different item
I'll use afterBreak one, I'll detect the item and damage the item durability only
let say you broke a block with 1 durability pickaxe
the pickaxe will break and itemStackAfterBreak should return undefined
so should i use Before or After?
It doesn't matter, depending on usage, if you wanna cancel the event use before, otherwise it's better to use after
Just make sure you have a check statement
if (!item) return;
Now anyway
So minecraft decides that js p.nameTag = `Β§cΒ§l${(p.getComponent('health').currentValue/2).toFixed(1)} Β§4Hearts Β§r${gemTypeColorCode[gID]}(${gID.charAt(0).toUpperCase()+gID.substring(1)})\nΒ§r${t !== undefined ? `Β§g[Β§8${t.split(':')[1]}Β§rΒ§g] ` : ''}${nC !== undefined ? nC.split(':')[1] : 'Β§7'}${p.name}Β§r`; has used something that isn't a function. [Scripting][error]-TypeError: not a function at updateNameTag (functions/mcUtils.js:29) at <anonymous> (functions/eventFunctions.js:83)
If anyone can tell me who is high, me or the game. Please do.
And yes t is team, it's valid, nC is name color, it's valid and p is player & it's also valid.
And gID is the gem ID and it's triple quadruple valid.
And also don't trust the discord highlighting, I can have inside of ${} inside of fine.
Great sir it's nC.split(':')[1] in my code
And ` works fine.
very confusing
Yes.
break in into lines to get the exact error location
I remember that the toUpperCase and toLowerCase methods work strangely
I decided to do the black magic voodoo of making my code unreadable to troll my friends when they try to edit the addon when it's on the server.
They make the whole string upperCased or lowerCased
That's why I only use it on char(0)
I will do that, thanks.
No no no. There are some strange situations there
Nah you'd be trippin' on air then
They work fine
import * as mc from "@minecraft/server"
import { ItemStack } from "@minecraft/server";
mc.world.beforeEvents.playerBreakBlock.subscribe(data => {
const player = data.player,
block = data.block,
inventoryComponent = player.getComponent(mc.EntityInventoryComponent.componentId),
item = inventoryComponent.container.getItem(player.selectedSlotIndex),
test = new ItemStack('mob_spawner', 1);
if (item.typeId != "minecraft:netherite_pickaxe" || block.permutation.type.id != "minecraft:mob_spawner") return;
block.dimension.runCommandAsync(`summon pig ${block.location.x} ${block.location.y} ${block.location.z} ~~`);
block.dimension.spawnItem(test, {x:block.location.x, y:block.location.y, z:block.location.z});
});
says there is an error in spawnItem
Why not just do block.location instead of your {}
I mean ur not editing the value?
Why not do player.dimension?
Also block will return undefined
Because it's already broken.
Who cares. maybe it's so convenient for him
There is no such thing as an undefined block, it comes with an air type
And here beforeEvents
also test var is not initialized
And I already found his problem
It's initialized
It doesn't need player.dimension
He just used a voodoo technique I use for initializing multiple variables
No errors in [code](#1067535608660107284 message)
Yeah you're right, I thought it was afterEvent
.
privilege system: https://wiki.bedrock.dev/scripting/script-server.html#beforeevents-privilege-system
no?
that is assigning a value to a variable that don't exist
Functions can throw undefined though however.
yes.. But when we try to get a block in an unloaded chunk
??????
I don't understand, what's wrong with the code?
this is not python
const test = ...
This is not the mistake
it is one of them
alr
Just do ```js
mc.system.run(() => {
block.dimension.spawnEntity("pig", block.location);
block.dimesion.spawnItem(test, block.location);
});
replace the command with
block.dimension.spawnEntity("pig", block.location);
And don't do that
I think you need system.run, since the pig is summoned, only the item is not.
Commands are automatically delayed I believe, but why even use this command? Native function exists.
The pig just ate the item
It's obvious
const var1 = ...,
var2 = ...
i guess i learned something new today
hm?
Java can do that as well.
never used java
I think most languages can do that as well.
@winter plaza
import * as mc from "@minecraft/server"
mc.world.beforeEvents.playerBreakBlock.subscribe(data => {
const {player, block} = data,
inventoryComponent = player.getComponent(mc.EntityInventoryComponent.componentId),
item = inventoryComponent.container.getItem(player.selectedSlotIndex),
test = new mc.ItemStack('mob_spawner', 1);
if (item.typeId != "minecraft:netherite_pickaxe" || block.permutation.type.id != "minecraft:mob_spawner") return;
mc.system.run(() => {
block.dimension.spawnEntity("pig", block.location);
block.dimension.spawnItem(test, block.location);
});
});
good to know
When you're too lazy to write the word "const"
lol
yeah i thought that was an error
ok
But not too lazy to write inventoryComponent instead of inv or at least inventory
It's a preference.
I usually write the vars in one line if they're related to one another. IE count and index.
i hate using the enum stuff for some reason
mc.EntityInventoryComponent.componentId
For some it is so convenient, but in my eyes it looks strange
That's cool buddy.
Moreover, they will no longer change the id, because it is in the stable version
Thanks!!
@burnt musk
you need buttons for all forms.
p.nameTag = `Β§cΒ§l${
(p.getComponent('health').currentValue/2).toFixed(1)} Β§4Hearts
Β§r${gemTypeColorCode[gID]}
(${gID.charAt(0)
.toUpperCase()
+gID.substring(1)})
\nΒ§r${t !== undefined ? `Β§g[Β§8${t.split(':')[1]}Β§rΒ§g] ` : ''}
${nC !== undefined ? nC.split(':')[1] : 'Β§7'}
${p.name}Β§r`;```
Bruh it says that .charAt() isn't a function π
Why this chat?
what is gID
String
try using the debugger
Gotten from a database
because its related to script api.
Debugger says it's fine
Very readable code
Ima log gID
Haha, sometimes...doing it all in one line is not always good.
Is it a joke or are u serious
I did not know, clearly.
just saw now.
It's prob a joke.. I ain't got no humor sadly :*(
Of course I'm serious. He's so understandable || no ||
function test(p: Player, gID: string, t?: string, nC?: string) {
p.nameTag = `Β§cΒ§l${
(p.getComponent('health').currentValue/2).toFixed(1)} Β§4Hearts
Β§r${gemTypeColorCode[gID]}
(${gID.charAt(0)
.toUpperCase()
+gID.substring(1)})
\nΒ§r${t !== undefined ? `Β§g[Β§8${t.split(':')[1]}Β§rΒ§g] ` : ''}
${nC !== undefined ? nC.split(':')[1] : 'Β§7'}
${p.name}Β§r`;
}
Debug result for [code](#1067535608660107284 message)
Compiler found 1 errors:
[36m<REPL0>.ts[0m:[33m4[0m:[33m6[0m - [31merror[0m[30m TS2304: [0mCannot find name 'gemTypeColorCode'.
[7m4[0m Β§r${gemTypeColorCode[gID]}
[7m [0m [31m ~~~~~~~~~~~~~~~~[0m
ESLint results:
<REPL0>.ts
1:10 error 'test' is defined but never used @typescript-eslint/no-unused-vars
People do need to learn how to debug on their own.
Yeah that's cuz debugger doesn't see it
debugger isn't on strict mode
I already debugged it before bruh
I know the debugger won't catch it.
I see, at least I can do it without icons
Debugged how? I'm not talking about using the bot.
Cuz it can't possibly understand the value from just the code.
Yes.. This bot often talks about errors that donβt exist.
you thought you needed a texture path for each button?
Well what are you talking about then?
(In calm tone)
Like, actually learn how to debug.
ah.
and... could an ActionFormData button be used to close the form?
Using console.log, breakpoints, etc.
Learn how to find and fix a problem in your code (without using my bot)
how do you use breakpoints with minecraft?
To understand the bug from the content log? Ye I do that but just sometimes I can't possibly figure out what's the problem when it depends on what the value is and the value is from a database, and I'm sure that it's string.
Console log in one line, yes yes
there's a method to close all forms that a player has open in the UImanager class
Ok, prove it. Add a console.log before the charAt to see the type and value.
ohh thanks, I'll try to do that π
Yeah that's the thing ima do rn, I'm seeing what gID is.
That doesn't mean I haven't made an error or something. It means I remember that I set it to string. Not that I logged it and found it was string.
We are gonna find out anyway, and I'm sure it's something stupid on my end.
guys
my bridge is broken again, i cant see the getComponent things
so
const enchant = itemStack?.getComponent("enchantable")?.getEnchantment;
if (enchant('silk_touch') { ,,, } is a thing?
astra, test:test, test:test
Please just type it all in one message.
Also the problem was I was passing a boolean as a value.... π
Just try and see :)
There we go, debugging.
My formatting when I'm lazy and tired be like:
I'll do it for u
You could check the docs.
the script isn't even 3% done
-# that not mine
Is the bot back? I keep trying yesterday and it's not working lol
getComponent auto completions just dont work when you use stable versions.
Guys, can we learn splitting your 40 page code into multiple functions, with each function does 1 task only please
ive tested this
Not entirely true.
beta versions aren't working at all
on bridge.
Have you tried casting it as well?
which version-beta is working?
vscode supremacy.
Also use vscode. Please
NO.
π
My function will do the work of 100 functions.
the current beta is 1.16.0-beta
And it will all be on one line.
on mobile
its not working on bridge
lemme show u
Stable - yes. Beta version - 1.17.0-beta
the whole thing just broke
thats in preview
unless I missed a changelog and 1.16.0 became stable
/mute smokeystack
Yes, that's what I wanted to say
Beta, Preview, interchangeable.
They hated him for speaking the truth.
And I will also use vars and not let or const and name them by keyboard smashing.
Not true
theres different betas for stable and preview
I am aware? I'm saying Beta and Preview are words that can be used interchangeably.
ah.
Context clues suggest that if they're talking about stable and beta, it means retail and preview.
were you talking to me beforehand?
You need to break code into functions if a piece of code is used several times
||Someone wants to say that they want to work||
@untold magnet [Scripting][error]-ReferenceError: Native function [ItemEnchantableComponent::getEnchantment] object bound to prototype does not exist.
Doesn't work, just make a function to return the certain Enchantment
For example
wait a moment
const tag = itemStack?.getTags;
if (tag('minecraft:is_pickaxe')) { ,,, } is a thing
it should be fine with enchantments too
right?
just use hasTag
thats an example
No it won't work probably
?
well it was a bad example
lol
getTags is an array
Native API doesn't allow that, normal javascript maybe
you need to use the incldues function
Is this the very moment when you are too lazy to write 3 letters?
i know guys
Why...on earth...would you use this?
...
its just a test
Then why the hell did you use it even tho you knew it
Unnecessary
guys, please understand, I'm not using that thing
its just to show i can use getEnchanment will work
like this
if(item == und()){
}
function und(){
return undefined
}
import { world, EnchantmentType } from '@minecraft/server';
const player = world.getPlayers()[0];
const inv = player.getComponent('inventory')?. container;
const main = inv.getItem(player.selectedSlotIndex);
const enchant = main?.getComponent('enchantable');
const get = enchant.getEnchantment({ id: 'fire_aspect' });
if (get) {
}```
Idk if this works, I forgor how to use this anymore
const und = () => { return undefined; }
Or something.
Damn... Even more unnecessary
lol
Just do ```js
const enchExits = (item, ench) => { return item?.getComponent('enchantable').getEnchantment(new EnchantmentType(ench)) !== undefined; });
@untold magnetBut seriously dude, please use the docs.
-# ik lazy to check docs
i, prefer finishing the script and test it out
there's also hasEnchantment
π .
class superComponent {
constructor(item, componentId) {
this.component = item.getComponent(componentId)
}
useMethod(id, value = undefined) {
return this.component[id](value)
}
}
erm, docs exist for a reason π€
Gets level, but cool yeah if 0 then it doesn't exist
i didn't find anything on it so, i prefer testing it out by myself
Then you suck at finding
You obviously haven't tried hard enough:
https://stirante.com/script/server/1.15.0/classes/ItemEnchantableComponent.html
Documentation for @minecraft/server
Dude, there's al lot of docs
The Microsoft, bedrock, stirante and most importantly jayly
Stirante on top.
Jayly on top.
Useless feature
Microsoft on top.
I use stirante
whats that
This is normal documentation
It's a soft micro
ohhh
I mean yeah, but not really
I'm surprised that people make some other documentation...
Soft as marshmallow
Breakable by just the small tiniest pinch
So I can use my gem ability "Hot Hands" and turn it into ashs?
As soft as a bedrock
Wrong emojis....
Blue locks s2 animations is shit. No questions asked
Alright then have a great day.
[Mean While]
WHY ISN'T THIS THING BURNINGGGGGGGGGGGGGGGG????
*Ability Hot Hands Is On Cooldown [Time Left: 193s] *
const enchant = itemStack?.getComponent("enchantable")?.getEnchantment();
if (enchant?.type === 'silk_touch') { ,,, } should work?
...
Should work.. Yes... You should get an error
SO USE getEnchants()
βοΈ
-# bumping this
It's too easy. You don't understand. We are not looking for easy ways
Error bout to be crazy
if (isn't enchanted with silk touch) {
if (is enchanted with fortune) { ,,, }
}
It. WILL. GIVE YOU AN ARRAY OF. ENCHANTS JUST USE SOME AND SEE IF IT MATCHS THE ENCHANT U WANTTTTTTTTTT
Dies
Nested ifs.
if isnt enchanted with silk && enchanted with fortune
Just do &&
calm down guys
If personally there is numerous things in the silk touch, I would just do an early return.
read docs.
That's all we want, it's for your own good.
That's a lot of emoji blud
Idk if this works lmao
if (['fortune', 'fire_aspect'].includes[item.getEnchantment()]) {}```
Just a hunch
const multiEncFuncs = [{
encs: ["silk_touch", "fortune"],
func: (item => {
// Code
})
}]
function test(item) {
for (let obj of multiEncFuncs) {
if (obj.encs.every(encId => item.getComponent("enchantable").hasEnchantment(encId))) obj.func(item)
}
}
Luv it... @untold magnet do you understand what's going on here?
i dont need to.
Just ignore the shi out of me.
I don't need a mother.
-# kids be like:
> Remembers Gem Abilities & Enchants & Effects Objects
lemme just finish the script and show it, and u guys will show me what is unnecessary things i did.
Why silck_touch???
Cause I'm the god of English
That gets annoying fast.
im not that bad on scripting
just my bridge-v2 is broken
You should use good practices yourself instead of relying on people to fix it for you.
But you're so unnecessary
and i cant understand the getComponent section well
Use the docs then.
|| Not noticeable||
It literally isn't that hard dude. We gave you the link.
Read docs, read docs, read docs, read docs, read docs....
-# reference.
What did you think? Is it that simple?
Huhh?
im asking about the only thing is broken on the website im using and i have no idea how it works
Until you solve problems yourself, you will not learn to solve problems yourself.
I mean, learn script without help of people and docs let's see
And we told you to use the docs.
i am using it rn
Is your script now done my good sir?
na
honestly just basic js/ts knowledge will help u understand
being able to read what is accepted into arguments is a big help
I'm not new on scripting
.
seems like you are
its just a getComponent that is broken on bridge, so i can't understand if I'm doing it right or not

then dont use bridge
simple
bridge is for beginners
if youre not a beginner, why use

I use bridge
i think bridge is quite doodoo
okay
useful for beginners
Why do I learn about newbie features when I'm no longer a newbie?
i dont have anything to coding with, except for bridge
vscode?
don't have it
then...
certainly, good for beginners, but in this case, for scripting api, it's better to use vsc
im on mobile
i use vscode + ts
lol

oh
should've mentioned that
can confirm that, I have a buddy that does this on mobile.
Just download any code editor and thatβs it.
yeah i started json UI on MOBILE and oh my
it was such a pain
it was over a year ago and it was with the app "koder"
yeah you are into json ui, ive seen you around in those channels.
json ui makes my brain hurt
i had an xbox and an iphone
i would upload the pack to mediafire and download it on my xbox
I make addons on my phone, although I have a computer...
acode 
gotta love mediafire
just to make sure im going right
const enc = itemStack.getComponent('minecraft:enchantable');
let silkTouch = enc?.getEnchantment('silk_touch');
let fortune = enc?.getEnchantment('fortune')?.level;```is it right? just to make sure.
is there any way to run something (e.g. some command) when they open certain action form page?
yes.
well
I would personally remove '.level' and just get the property when checking it in a conditional statement
form.show(player).then(param => {
// running something
});
right, i will be detecting the fortune level on functions anyway
let menu = new ActionFormData().title("My form")
menu.button("Super button")
menu.show(player).then(data => {
if (data.selection == 0) {
player.runCommandAsync("say Super button")
}
})
halo sent code already
I don't write that fast
also stop using commanddsss
anyone have some ideas on how i would "pull" players towards a location?
player.sendMessage('SUPER DUPER BUTTON')
applying knockback?
appl-
Whisper of mathematics and applyKnockback
...yeah
lol
math does indeed suck
its for my whirlpools
if they are in water and near a whirlpool it can sometimes suck them into it and they cant swim out of it
@unique dragon @warm mason will try π
is it an entity?
i dont think you need math then
I have a couple of functions that greatly simplify working with vectors.. But I wonβt give them to you because Iβm evilπ
how so
just applyknockback to the direction of the entity
hm
Needed to determine direction
Still need math
im talking about what I was thinking
ok
imported UIManager and didUIManager.closeAllForms(sourceEntity);
but when it runs it says it's not a function ([Scripting][error]-TypeError: not a function at <anonymous> (main2.js:1415))
please what am I doing wrong?
I tried to run the function through an UIManager object (through new UIManager()), but then it says No constructor for native class 'UIManager'
UIManager doesn't have any constructor so idk what to do
I'm pretty new with this πͺ
the instance of UIManager is uiManager
if (id?.matchAll('normal:ore', 'deepslate:ore')) {eDrop(block, loc, fortune, 'base:drop'); if (Math.random() <= 0.25) eDrop(block, loc, fortune, '25%:drop')};```does it have any issues?
I have thisJavascript const uiManager = new UIManager(); uiManager.closeAllForms(sourceEntity);but it says No constructor for native class 'UIManager' π€¨
No, the constructor of UIManager is private, so you only need to import uiManager from server-ui
already imported it at the beginning of my .js file
import { ActionFormData, UIManager } from "@minecraft/server-ui";
Math.random() * 10.0 will generate random numbers from 0.1 to 10.0, if the number is 2.5 or less it will run that function, right?
the object you need to import is uiManager, which is an instance of UIManager
it works now, thank you @distant gulch π π
my first "script" was in the early betas
... written on my xbox one s using online db compiler π€£
updated
is it possible to get the type id of a falling block entity?
and i mean by that the typeId of the block that is falling, because the typeId of the entity is minecraft:falling_block, and that's not really useful
no
Is there a way to get the face of a block you mined, or do I have to jerry rig something to find out?
you'd need to check in before break block the head direction of the player perhaps?
faceLocation
should be on the event args
Does anyone know about afterEvents.playerInputPermissionCategoryChange? Why isn't it being fired in 1.21.44 when its documented? Do I have something wrong or is this expected behaviour?
Im assuming in playerBreakBlock, but I only see block, cancel, itemstack, and player
ah nvm that's only for interact
you should be able to figure out the player's facing by examining their head
you'd have to do some maths yeah
Welp...math I go
@near siren
#1067535608660107284 message
Not necessarily accurate for blockFace but at least you can get the players facing direction. Alternatively you could do entityHitBlock.
The god himself has mentioned me, thank you. I'll see what I can do
How can I cancel block placement in stable?
playerPlaceBlock... Yes it's stable now
In latest stable or preview?
Latest stable... 1.21.44
no
Huh?
Ohh yeah mb, I thought you're saying it's should be beta
and check for all blocks then cancel interaction which equals placement?
No. If you need to check only specific blocks, then you can simply compare the ID of the item in the playerβs hand
Then check if the item ID is in the list of block types
Will give it a shot, thanks!
Impossible
Mojang didn't say anything about it
gonna have to wait until the 2025 api qna
Not sure if you're asking for a way to get the light_emission value of a block, or just the light level at a particular location. (I guess there's not too much difference since you can find the former by placing a block in the world and testing the light at that location)
There's no native API call for this, but you can get the light level by using an invisible temp entity that triggers an event based on a molang query for the light level. I just posed an example: #1306499809451966514 message
ty
guys, I'm too curious if i can do this thing:
having an array that has multiple different blocks types, inside of 'playerBreakBlock' component theres a tiny system that requires the blocks ids in the array, i can do that simply by using 'array.includes' but thats not what i need specifically,
I'm wondering if i can use the Ids inside of that array in a specific way.
like giving each ID in the array a number
instead of using this:
+
if (eBlock.type.id === 'block:one') aFunction(eBlock, 'block:one');
if (eBlock.type.id === 'block:two') aFunction(eBlock, 'block:two');
+
i can make it simpler by using the array number,
like this:
if (id1, something) aFunction(eBlock, id1)
idk if i explained it right but i hope u guys
-
understand what im asking for.```so i dont have to write the same Id again and again
if it is possible, show me how bec i need it.
Im confused
Do you want to set specific functions to specific blocks but have a handler for it?
i dont want to use the same ID that is inside of the array multiple times
const array = [ 'block:one', 'block:two' ]
// playerBreakBlock
if (eBlock.type.id === 'block:one') aFunction(eBlock, 'block:one');
if (eBlock.type.id === 'block:two') aFunction(eBlock, 'block:two');```i dont wanna do this if i can use the ID directly from the array
const array = ['block:one', 'block:two']
if (array.includes(eBlock.type.id)) aFunction(eBlock, eBlock.type.id)
?
if i can use a method that will make me able to use the IDs directly from the array will be more efficient
no
Oh
i dont want to write the block ID multiple times,
const array = ['block:one', 'block:two']
const id = eBlock.type.id
if (array.includes(id)) aFunction(eBlock, id)
like giving the array multiple sections, each section will have it own ID, and i can use that ID to run the function and the ID will take the blocks ID inside it
Oh
ohhh
okay
const array = [
{
id: 'block:one',
code: () => {world.sendMessage('block one')}
},
{
id: 'block:two',
code: () => {world.sendMessage('block two')}
}
]
const found = array.find((f) => f.id === eBlock.type.id)
if (!found) return
found.code(found.id)
?
still kind of confused
ngl
Also idk if I wrote it correctly, am on phone rn
chatgpt ahh moment
I don't use chat gpt
bro has not seen how I code ig
I use that array stuff all the time
i think it was array.flat, or array.filter
or array.findIndex
it is findIndex
no?
const tridentData = CustomTridents.find((f) => f.itemID == item.typeId)
I've never used findIndex
only find
GUYS, do not tell me to use docs bec array things aren't available in docs i know
Basic JavaScript websites tutorial exists π€·
full thing
const array = [
{
id: 'block:one',
code: (id: string) => { world.sendMessage('block one') }
},
{
id: 'block:two',
code: (id: string) => { world.sendMessage('block two') }
}
]
world.beforeEvents.playerBreakBlock.subscribe((data) => {
const eBlock = data.block
const found = array.find((f) => f.id === eBlock.typeId)
if (!found) return
found.code(found.id)
})
in ts though, got on my laptop now
link;
#1306560102668435457
Quick question, what do you guys use for scriptevents? Switch? Ifs? or Objects?
why not use multiple listeners?
One for each script event?
yes
the 3rd thing you're doing in the screenshots is pretty much just a overcomplicated version of that
Nah I think making a wrapper arround a single listener is the best as it is less calls from native. Using a lookup is always faster then if statements. Both switch and objects can do that. But the way you implemented it with the .forEach it is quite inefficient. The best way would be to have an object or a map where the id is the key and the value your function. This would ensure a constant lookup time. But tbh it only matters with big data sets here it will not matter like at all unless you are running a lot of them in a tick
I see
the lookup in this case would be slower than using multiple listeners
native listener iteration is faster than in the JS runtime
I do not belive that. You'd have to drop the benchmark
Multiple listeners would be much slower, because every listener gets called every time a script event is received.
Generally you only want to have one type of subscriber for each world event type ideally. Unless they offer filtering at the subscription level, then maybe multiple would be fine.
that's completely wrong
@wintry bane The answer to this question is definitely objects, but not in any of the ways you have in the screenshots. You don't want to use arrays at all. You want an object where the key is exactly the script event id and the value is the function you want to call.
const events = {
"id:event" : functionA,
"id:eventb" : functionB
}
Then in the script event you do
events[e.id]()
To call it
Which part do you disagree with?
the entire statement
What are you discussing?
- calling a double recursive function in the JS runtime, and allocating new variables,
vs - iterating over an array of functions in native C++
second one is gonna be faster every time
I think a single subscription is only needed when you want to track each subscription, for example, to make fake event calls
sure but it'll be slower
Not too much
If you don't have 500 events, that's fine.
I don't know what you mean by "double recursive" here, but a lookup in a JavaScript object (which is a hash table with O(1) lookup complexity) is always going to be faster than iteration ( O(n) ) whether it's on C++ or JavaScript.
Maybe I'm missing something though, do you have any example code of the way you prefer to do it?
I was talking about the case that the original asker showed
in the screenshots
hashtable is O(n) worst case and O(1) best case
average time complexity is actually O(1+n/k) where k is the size of the hashtable
Big O Notation π
A developers friend when one has good relationship with it.
ngl, i still forget what those hashing methods are and just proceed with whatever comes up to mind
const gM = player.getGameMode('creative');
if (gM) return;```should return when the player is creative?
Yeah. Try it and see.
const mode = player.getGameMode();
if (mode === 'creative') return;```is how i should do it.
Sure, whatever.
Why playerPlaceBlock beforeEvents was working on armor stand before but now itβs not?
bec it was a bug and the armor stand is entity, not block
i guess^
No itβs because when I bought the White House I told them to change it
it never was
it was
what version
Are you sure it wasn't another event triggering it?
1.21.21
yeah it was opening menu
huh
Yes
I don't think I follow what you're saying (maybe we're agreeing with each other?), there were 4 screenshots posted and none of them had multiple subscriptions in them.
Script events don't support listening to a specific "namespace:id" combination, so you can either:
- have each subscription check the event id with an
ifstatement, in which case we're checking the event id in the javascript context and not saving any CPU cycles (still looking at O(n) and it's no faster than just using a bunch ofifstatements):
system.afterEvents.scriptEventReceive.subscribe(
(e) => {
if (e.id === "mynamespace:function1") {
/** Logic for script event 1 */
}
}
);
system.afterEvents.scriptEventReceive.subscribe(
(e) => {
if (e.id === "mynamespace:function2") {
/** Logic for script event 2 */
}
}
);
// ...
- Or are you suggesting that all of the script events would have a different namespace and we would be filtering by namespace and ignoring the event id when making the subscription like this where
/scriptevent function1:aaawould hit the same listener as/scriptevent function1:bbb?
system.afterEvents.scriptEventReceive.subscribe(
(e) => {
/** Logic for script event 1 */
},
{ namespaces: [`function1`] }
);
// ...
Because I just tested both option 1 and 2 above and with 10,000 script event listeners and option 1 is 10,000 times slower than the method I suggested with a Map, as expected. And option 2 (letting the game engine handle the filtering of namespaces) is a little faster than option 1, but still 2,000 times slower than routing with a Map.
with custom animation
do you have one?
uh, guys..
im using this method for damaging my tools:
function dmg(itemStack, player, enc) {
if (!enc) dur(itemStack, player);
if (enc === 1 && Math.random() >= 0.25) dur(itemStack, player);
if (enc === 2 && Math.random() >= 0.34) dur(itemStack, player);
if (enc === 3 && Math.random() >= 0.49) dur(itemStack, player);
}```so, there's a more efficient way to do it using a switch case or syntax thing, so can u guys edit it?
yeah
give me a sec
@buoyant canopy
you may need to edit it for first person camera
is he making 3D modelled things that have normal attack animation in FP?
thank you very much
how do i call it?
player.playAnimation("animation.steve.swing")
i put it in a resource pack/animations folder and used that command but my hand didn't swing?
it should...
let me se how i implemented it
i just did
source.playAnimation("animation.steve.swing")
and it worked fine
i am using it in a playerInteractWithBlock beforeEvent(system.run())
check the third person camera?
no swinging
i will send a screenshot
weird
let me try again
this weird
it was working in first person camera but now it doesn't
maybe i need to add the item bone there
for me, it doesn't even work in 3rd camera
do you have another animation or something?
i think i figured it out
nevermind
so when i run the command you used in the video it works
but not when i call it in the script
it does work even without the parameters
the command that is
it work with script too
or i think so?
it works! i don't know what i did, but it works now???
yeah
lol
but first person is still broken
it need the item bone to move
let me try making it do so
My addon is fully functional now Lol
how? did you animate it
because i am in survival bone meal is consumed and it acts like it's animated
this didn't work
my guess is i should make it over ride
it's completely still in creative tho
it's kinda a mockup fix, but i will go with it, thanks a lot for helping me today!
your wlc
didn't work either
maybe because view bobbing is off?
it is not
world.beforeEvents.playerBreakBlock.subscribe(({ itemStack, block, cancel }) => {
const { x, y, z } = block?.location;
const silkTouch = itemStack?.getComponent('minecraft:enchantable')?.getEnchantment('silk_touch');
if (silkTouch) if (block?.typeId?.startsWith('exe:') && block?.typeId?.endsWith('_ore')) { system.run(() => {block?.dimension.runCommandAsync(`fill ${x} ${y} ${z} ${x} ${y} ${z} air destroy`)}); cancel = true};
})```this is not cancelling the block distraction, why?
specifically cancel = true isn't working
@distant tulip, i need help with this sh!t
you can't do it like that
i want to cancel the block break
world.beforeEvents.playerBreakBlock.subscribe((event) => {
const { itemStack, block } = event
const { x, y, z } = block?.location;
const silkTouch = itemStack?.getComponent('minecraft:enchantable')?.getEnchantment('silk_touch');
if (silkTouch) if (block?.typeId?.startsWith('exe:') && block?.typeId?.endsWith('_ore')) { system.run(() => {block?.dimension.runCommandAsync(`fill ${x} ${y} ${z} ${x} ${y} ${z} air destroy`)});
event.cancel = true};
})```
cancel = true was working before
you must do event.cancel = true
yah i was using this way
You are destructuring the cancel property from the object and assigning it to a variable. Then you are modifying the variable. When you modify the variable the property of the object is not modified as they are two different instances. You have to modify it directly.
anyways this will no longer happen,
compiler bot is just deadass not working for me
the bot is offline at the moment
so wait for jayly to fix em
{
"format_version": "1.20.0",
"minecraft:item": {
"description": {
"identifier": "item",
"category": "Items"
},
"components": {
"minecraft:max_stack_size": 1,
"minecraft:icon" : {
"texture": "item"
}
}
}
}
Does someone know why when i try to set dynamic properties in my item it says "Cannot set dynamic properties on stackable items" but this item isn't stackable, it's max _stack_size is 1 and it was working good before.




