#Script API General
1 messages · Page 27 of 1
const { dimension, location: { x, y, z } } = block;
dimension.spawnParticle("minecraft:crop_growth_emitter", { x, y: y + 1, z });
thanks!!


im back
why 'hasTag' dont work in here?
itemRegistry.registerCustomComponent("aliien:on_consuming", {
onConsume: (event) => {
const item = event.itemStack;
const player = event.source;
player.sendMessage("item1");
if (item.hasTag('custom')) {
player.sendMessage("item2");
player.runCommand(say hi)
}
}
})
guys
i somehow found a log
how?!
const { x, y, z } = block?.center(); at this line
that happened when i left the world once
why does this fails? js console.warn(pEquipment.getEquipment(`Mainhand`).getComponent(`minecraft:cooldown`).isCooldownCategory(`mh_soul_crystal`))
is there a way to check for charged creepers in specific
you can detect if the minecraft:become_charged event triggers
then set a tag, or dynamic property on them
is this possibel without script
possible*
in filters, you can check if it has the minecraft:is_charged component
I save the structure with the mob id and add the mob id as the item's lore
Is System.waitTick the same as setTickTimeout?
itls like
const {x,y,z} = undefined?.center()
undefined cant be deconstructed into x,y,z
why do not you use unsubscribe instead?
Does anybody know why this happens?
I have my block version to 1.21.20 and it doesnt work. I have tried a couple of things and still... Any help can be usefull! TwT
that aint script API
a
maybe try #1067876857103536159?
you can use getItemCooldown method from Player
/** @type {boolean} */
const isOnCooldown = player.getItemCooldown("mh_soul_crystal") > 0;
world.runCommandAsyc(`gamerule keepinventory true`);
});```
guys why this doesn't work
world cant run command
you need to get dimension
ok thanks
import { world } from "@minecraft/server";
world.gameRules.keepInventory = true;
How can I detect if a players interacts with an block with an empty hand?
import { world } from "@minecraft/server";
world.beforeEvents.playerInteractWithBlock.subscribe(({ player, block, itemStack }) => {
if (itemStack) return;
// rest here
});
thanks
Anyones
How to fix this
🤔
import { system, world } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
import "./combatlogger";
world.afterEvents.playerSpawn.subscribe(evd=>{
const player = evd.player;
system.runInterval(() => {
system.run(() => NotPlayedDialogue(player.hasTag('NotPlayed')))
}, 15);
function NotPlayedDialogue(viewer) {
const dialogue = new ActionFormData();
dialogue.title('§l§a『遊玩條款』');
dialogue.body(`§l§b嗨嗨!§f歡迎你來到了本遊戲§8【§6職業§cPVP §7v1.0§8】§f我是這張地圖的創作者——§c紅石§f。在開始前,可以的話請先仔細閱讀本圖的規則,謝謝ww§a本地圖§f的玩法十分簡單,你可以在這裡與所有玩家進行一場§b酣暢淋漓§f的§c戰鬥§f!!此外,本地圖也有商店系統,你可以從商店購買小道具!這些道具會在戰場上給予你一些特殊的能力,每個道具都可使用§e金幣§a購買,§e金幣§f可通過§c擊殺§f玩家§a獲得§f。說了那麼多,是時候來介紹§a本地圖§f的規則了:)
以下是§a本圖§f的規則:
-不要使用§c外掛§f(這樣會破壞遊戲平衡
-不要罵人(保持友好
-不要刷屏
-不要惡意使用bug(及時報告管理員可得§e獎勵
§f最後,點擊下面的§b按鈕§f來加入§a遊戲§f!!`);
dialogue.button('§l§b點擊這裡§a加入§e遊戲§b!!', 'textures/ui/icon_deals');
dialogue.show(viewer).then(({ selection, canceled }) => {
if (canceled) return;
if (selection === 0)
{evd.player.runCommandAsync('tag @s add Played'),evd.player.runCommandAsync('playsound random.toast @s'),system.runTimeout(()=>{evd.player.runCommandAsync('replaceitem entity @s slot.hotbar 4 compass 1 0')},35);}
})
}
})
I need to show the form for player who has tag 'NotPlayed'
But it always have issue
theres no "viewer"
passing a boolean
lol
hasTag doesnt return Player
if (player.hasTag('NotPlayed')) {
NotPlayedDialogue(player)
}
world.afterEvents.playerSpawn.subscribe(evd => {
const player = evd.player;
if (player.hasTag("NotPlayed")) system.runTimeout(() => { NotPlayedDialogue(player) }, 60)
})```
also why an interval for that?
use this @quick shoal
i believe its because the form doesnt show and close when the player is spawning in
since player spawns first and then join
that won't stop if it was working xd
or you can use forceShow function
?
const forceShow = async (player, form) => {
while (true) {
const resultData = await form.show(player);
if (resultData.cancelationReason !== "UserBusy") return resultData;
}:
};
import { system, world, ItemStack } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
import "./combatlogger";
world.afterEvents.playerSpawn.subscribe(evd => {
const player = evd.player;
if (player.hasTag("NotPlayed")) system.runTimeout(() => { NotPlayedDialogue(player) }, 200)
})
async function NotPlayedDialogue(viewer) {
const dialogue = new ActionFormData();
dialogue.title('§l§a『遊玩條款』');
dialogue.body(`§l§b嗨嗨!§f歡迎你來到了本遊戲§8【§6職業§cPVP §7v1.0§8】§f我是這張地圖的創作者——§c紅石§f。在開始前,可以的話請先仔細閱讀本圖的規則,謝謝ww§a本地圖§f的玩法十分簡單,你可以在這裡與所有玩家進行一場§b酣暢淋漓§f的§c戰鬥§f!!此外,本地圖也有商店系統,你可以從商店購買小道具!這些道具會在戰場上給予你一些特殊的能力,每個道具都可使用§e金幣§a購買,§e金幣§f可通過§c擊殺§f玩家§a獲得§f。說了那麼多,是時候來介紹§a本地圖§f的規則了:)
以下是§a本圖§f的規則:
-不要使用§c外掛§f(這樣會破壞遊戲平衡
-不要罵人(保持友好
-不要刷屏
-不要惡意使用bug(及時報告管理員可得§e獎勵
§f最後,點擊下面的§b按鈕§f來加入§a遊戲§f!!`);
dialogue.button('§l§b點擊這裡§a加入§e遊戲§b!!', 'textures/ui/icon_deals');
dialogue.show(viewer).then(({ selection, canceled }) => {
if (canceled) NotPlayedDialogue(viewer)
if (selection === 0) {
viewer.addTag("Played")
viewer.removeTag("NotPlayed")
viewer.runCommandAsync('playsound random.toast @s')
viewer.getComponent("minecraft:inventory").container.setItem(4, new ItemStack("compass"))
}
})
}
hey, to the people here is it possible to create a chest? or imitate it? im trrying to make a custom chest with special sprinkles on it
or
or
Thanks
which is better when it comes to repeating stuff, system.runInterval() or system.run() that runs function?
runInterval
run is intended for deferred execution so that no problems arise, and runInterval is for repeating code, and there is also a delay and there is no need to reinvent the wheel
why did you like "run" so much?
just testing
I even have a function for interval
function interval(func, speed, loop, onStop = undefined) {
let interval = system.runInterval(() => {
try {
func()
loop--
if (loop <= 0) {
system.clearRun(interval)
if (onStop != undefined) {
onStop()
}
}
} catch (e) {
system.clearRun(interval)
console.warn("Interval error: " + e)
}
}, speed)
return interval
}```
looks great
for (let i = 0; i < inventory.size; i++) {
const invItem = inventory.getItem(i);
if (invItem && invItem.nameTag.startsWith("§l§aVIP Kit")) {
if (invItem.amount > 1) {
invItem.amount -= 1;
inventory.setItem(i, invItem);
} else {
inventory.setItem(i, null);
}
player.dimension.getBlock(block).setType("minecraft:air");
break;
}
}
You cant use startsWith?
you can
bruh, u can
you... can
how bro i got a error with this statment
invItem && invItem.nameTag.startsWith("§l§aVIP Kit")

why not just use dynamic property for the check
using nametag for item check seems very prone to breaking
also there could be a typo
and its case sensitive too
what is the error
limited on items
thats why i did include
how do you setblock again on a location?
can somebody lead me to the docs of that?
is there any way to apply knockback downwards? (-vertical)
source.applyKnockback(view.x, view.z, 0, -4);
not work
try 0,0,0,-4?
are you sure there are no errors in the code? this should work
no error
not work
does knockbacking upward work
work
and you sure theres nothing below the target
yes
post the code
it doesnt work on player?
it should work on player
...
btw, Is there a method for players to stay in air for a while without using teleport?
How do i check the data id of a item?
world.afterEvents.itemUse.subscribe((ev) =>{
const item = ev.itemStack
const player = ev.source
if(item){
player.sendMessage(`${item.typeId}`)
}
})
Netherite armor and resistance effect reduce knockback force
yes
but its alot of math

I figured out a way to do this without a ton of math and armor accounting
you can't do that
if you need potions you can try using the createPotion method and the "mineraft:potion" component
oh thanks man
how to use debugger in #debug-playground
hold the message you want to debug
and use apps, then select debug scripts
But I want let it repeat to show
runtimeOut cant repeat
Wait
runInterval is repeating
The canceled will show again?
But it have issue
@warm mason I think u did the effect I wanted
Because if cancel the form will show again right?
I will test it later ,thanks
How to check if it’s not player first spawn using
world.afterEvents.playerSpawn.subscribe?
world.afterEvents.playerSpawn.subscribe(data => {
if (data.initialSpawn) return;
// Code here (if player respawned from death)
})
server.world.afterEvents.worldInitialize.subscribe(() => {
for (const p of server.world.getAllPlayers()) {
setTask(p);
}
server.system.run(() => {
try {
server.world
.getDimension(MinecraftDimensionTypes.Overworld)
.runCommand("/tickingarea add circle 0 0 0 4 true_spawn true");
} catch (e) { }
});
server.system.runJob(gameLoop());
});
import { GameMode, world } from "@minecraft/server";
import { isGameStarted } from "..";
let playersLeft = 0;
export function getPlayersLeft() {
return playersLeft;
}
export function* gameLoop() {
while (true) {
if (isGameStarted()) {
playersLeft = world.getPlayers({ gameMode: GameMode.survival }).length;
}
yield;
}
}
This seems to slow down the game
When I remove the add-on, the world/server runs fine
I think you want to use system.runInterval instead of system.runJob
system.runInterval will give you the consistency than system.runJob
But I think it depends on what "isGameStarted" even does.
I can share that code as well
It really just returns a boolean value
export function isGameStarted() {
return gameStarted;
}
How do you detect the name tag of an entity?
entity.nameTag
Is there not a player.isWalking? What's a sollution
do you need to detect player movement?
I just need to know if the player is walking yeah. Right now i'm just comparing if the velocity is not all 0
Is there a method of generating a map item with pixels set to colors dynamically? Only generating map art then teleporting player?
I want to generate small 2D images at runtime. What's the best way?
I figured I'd start by trying with maps. I had some success with particle effects. I'm sure there are some cool methods to do this?
So i'm fairly new to this scripting thing but can anyone help me out why i can't run this command but it works with any other minecraft commands, only fill command seems to not work. It is ticking custom component for a block.
i tried with functions cuz it didn't work like this fill ~-1 ~ ~ ~-1 ~ ~ sp:small_celestite_bud ["minecraft:block_face"="west"] replace air
but functions with fill command also don't work
other commands work like "time set night" for example works fine only "fill" seems to not
Animation controller 
allow me 😏
oh wait, I just did !player.isSprinting, !player.isSneaking, !player.isGliding, then isMoving, which is
const isMoving = MathRound(player.getVelocity().x) != 0 || MathRound(player.getVelocity().y) != 0 || MathRound(player.getVelocity().z) != 0;
``` @wary edge
pretty sure that's everything? Kinda just looking at my stamina system rn
i used to think there was a player.isMoving, swear there was.
mandela effect..
that is a query function
const isMoving = (entity => { return ['x','y','z'].map(axis => entity.getVelocity()[axis]).every(value => value == 0) })
what does MathRound do differently from Math.round 🤔
Anyone please 🥺
Cant use that
Yeah i just used a areVectorsEqual func
...
the dimension is running the command, so check if your using "~", the blocks are gonna be placed there: x: -1, y: 0, z: -1
Solution:
const { dimension, location: loc } = block;
const offset = { x: loc.x - 1, y: loc.y, z: loc.z - 1 };
const checkBlock = dimension.getBlock(offset);
const perm = block.permutation.getState("minecraft:block_face");
if (checkBlock?.typeId === 'sp:small_celestite_bud' && perm === "west") {
dimension.setBlockType(loc, 'air');
}
#1292588668627718155
I've seen addons where they summon a Minecraft block and that Minecraft block takes the texture of the ground so example if the texture of the ground is dirt it will summon a block of dirt, does that work through scripting?
minecraft developers please add a player swing event 🫠
no
particle in a custom entity and pass these to it
query.surface_particle_texture_coordinate
query.surface_particle_texture_size
query.surface_particle_color
the particle need to have the terrain texture
Oh thanks
How do I store a method? I have objects that I made for a Daily Reward System that look like this:
,
cookedChicken:{
weight: 100,
quantity: 24,
slots:1,
displayName: "Cooked Chicken",
description: "Some Free Food!",
icon: "textures/items/chicken_cooked",
method: ((p,q) => cookedChicken(p,q))
},
But I can't get the method property to store alongside the rest of the stringified object. Is there a means to do this that I'm just not aware of? If there isn't, is there a way to get the object back?
const foo = {
val: "test",
bar() {
return this.val
}
}
console.log(foo.bar()) //return test
oh stringifying function?
nah
Just stringify the data, then process it with premade function
Or... you can do function.toString() then use eval or smt
is system.run read only?
No
does setting dynamic property requires priveledges?
like can i set dynamic property before the player leaves?
world.beforeEvents.playerLeave.subscribe(({player}) => {
const date = new Date()
const leaveDate = date.toISOString()
player.setDynamicProperty("last_seen",leaveDate)
})
u should try
how tho, i don't have other devices to test player leave
Yes
Dynamic property set does not need privileges, and you can set before player leave.
okay thank you
EntityHitBlockAfterEvent is an inaccurate name i feel
that event is more like when you start the process of mining
oh. Cuz i'm trying to get a projectile to have an owner of the player shooting it and it's not setting the value.
// itemStartUse event
const bullet = player.dimension.spawnEntity(projectile, player.getHeadLocation());
const projComp = bullet.getComponent("projectile");
system.run(() => {
projComp.owner = player;
})```
this is being taken care of with the `itemStartUse` event.
Why do I keep getting an error that says: TypeError: 'Head' is read-only.
import { Block, BlockPermutation, Direction, EntityComponentTypes, EquipmentSlot, Player, world, system } from "@minecraft/server";
system.run(() => {
const headSlot = Player.getEquipment(EquipmentSlot.Head = "Head");
world.sendMessage(headSlot);
})```
because you are trying to reassign the head property...
the code is wrong
just have the string "Head" or EquipmentSlot.Head.
bruh, that's the Player class
lmao
xd
hes not getting the equippable component
import { system, world } from "@minecraft/server";
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
const equipment = player.getComponent("equippable").getEquipmentSlot("Head");
player.sendMessage(equipment?.typeId);
}
});
@tawny jungle
player.sendMessage(equipment?.typeId) —> player.sendMessage(equipment?.typeId??"")
(sendMessage only accept string, undefined can throw errors)
thanks guys
...And getEquipmentSlot() —> getEquipment()
ItemStack Class is simpler to work with than goofy inconsistent ContainerSlot Class
my real issue being
i dont know how any of this works
but thank you, i will continue to learn 🫠
but what if I only wanted the info of the player in question?
getEquipmentSlot returns a container slot, which represents the physical “slot” in the entity/player inventory
getEquipment returns an ItemStack, which represents an item, and an item alone- it kinda grabs a snapshot of the item in the slot when called, so any changes to it won’t show up on the item in the inventory.
ah yes
is there a specific reason for this?
you'd think we'd be able to modify the itemstack directly...
S’ what container slot is for
You can also create ItemStack references that don’t actually exist anywhere in the world, and only are a thing in your code.
Item stack doesn’t have to be tied to a slot- spawn item, for instance, or entity component item stack.
Why the two locations? You only need one
The third parameter for the particle is molang variable stuff
Forget it, I only realized the error when I got there.
Also you can just pass in location to the second parameter, you don’t have to destructure it the way you did 👍
Ok, Thanks for the help
If you wish to add/subtract, then yeah you need to destructure, but just as-is you don’t have to.
btw its showing an error
also is there a way to make so that this doesn't show an infinite number of responses

thanks
Yeah, that fixed it. Thank you!!
what am I doing wrong to get this to set my helmet slot to the item im holding? Im not getting any errors, just nothing
const itemStack = data.itemStack;
const player = data.source;
system.run(() => {
for (const player of world.getAllPlayers()) {
const equipment = player.getComponent("equippable").getEquipment("Head");
const reach = player.getBlockFromViewDirection({ includeLiquidBlocks: false, includePassableBlocks: true, maxDistance: 1 })?.block;
if (((equipment?.typeId??"") === "") && !((reach?.typeId??""))) player.getComponent("equippable").setEquipment("Head", itemStack);
}
})```
const player = data.source
ah
thats my bad
i forgot to include that in the snippet
i do already have that
i added it
Don't use getPlayers
what do i replace it with??
as in just this? or perhaps keeping the const?
const itemStack = data.itemStack;
const player = data.source;
system.run(() => {
const equipment = player.getComponent("equippable").getEquipment("Head");
const reach = player.getBlockFromViewDirection({ includeLiquidBlocks: false, includePassableBlocks: true, maxDistance: 1 })?.block;
if (((equipment?.typeId??"") === "") && !((reach?.typeId??""))) player.getComponent("equippable").setEquipment("Head", itemStack);
}```
this seems to have the same issue of no errors and nonfunctional
Check your if statement logic
especially that bottom one
probably syntax error
world.beforeEvents.itemUseOn.subscribe(function (data) {
const itemStack = data.itemStack;
const player = data.source;
system.run(() => {
const equipment = player.getComponent("equippable").getEquipment("Head");
const reach = player.getBlockFromViewDirection({ includeLiquidBlocks: false, includePassableBlocks: true, maxDistance: 1 })?.block;
if (((equipment?.typeId??"") === "") && !((reach?.typeId??""))) player.getComponent("equippable").setEquipment("Head", itemStack);
});
});
Thank You!
He said no error. 🤦♂️
Syntax error would immediately show up when the code is being compiled.
script for placing a block above a player when holding an item?
i've been trying to make a script where if a player holds an item in its mainhand it will place a block above the player like glowstone but no luck
import { world, system } from "@minecraft/server";
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
const item = player.getComponent("minecraft:equippable")?.getEquipment("Mainhand");
if (item?.typeId !== "your_item_id") continue;
const { x, y, z } = player.location;
player.dimension.setBlockType({ x: Math.floor(x), y: Math.floor(y) + 2, z: Math.floor(z) }, "your_block_id");
};
}, 1);
I'll try that out ty i was using equipment slot
will the block be centered? or offset? just asking?
you can use the .center() and bottomCenter() methods to get locations like { x: 1.5, y: 1.5, z: 1.5 } and { x: 1.5, y: 1, z: 1.5 }
every time i open a json file in vscode i have to set the format to jsonc manually, how to make it automatic?
Not a scriptapi question
👀
yes, but the people who deal with the script api are the most familiar with vscode out of the people i have access talk to.
thank you very much
Still, please ask in the proper channels
I don't see a channel for VSCode
would that go under #add-ons or #off-topic ?
Probably
Either one can work
well i initially had it to send a message in chat when the same criteria was met and that was successful, but the part afterwards wont work
yeah, vscode is reporting no syntax errors
but thanks
Getting back into scripting.. Can som1 let me know why this won't work?
const scores = [
"ach-time",
"ach-ks",
"ach-kills",
"ach-deaths",
"ach-eW",
"ach-blocks",
"ach-crates",
"ach-pres",
"claimedTier",
"exp",
"deaths",
"kills",
"Money",
"sec",
"min",
"hour",
"day",
"ks",
"Bounty",
"CT",
"kd",
"Koth",
"afkTimer",
"Prestige",
"Staff",
"blocks",
"crates",
"Particle",
"Particles",
"BPTier",
"DonoTokens",
"NColor",
"CColor",
"eventsWon",
"freeClaimedTier",
"PremClaimedTier",
"BubsClaimedTier"
].forEach((scores), world.scoreboard.addObjective(scores))
.forEach((objective) => world.scoreboard.addObjective(objective));
ty
but put this in try catch block
if objective exists and you are trying to add it, you gonna end up getting an error
it works but now whenever i leave a block it stays behind but updates the block im at
guys!
do u know how custom chest is made?
it looks like tile entity
like if i made the entity hitbox to cover the block then player can interact and open its inventory
but then player cant break it
just files
inventory thing I believe inside of a entity
system.run(() => {
entity.remove();
});
Before events cannot modify the world
for before events, use system
await system.waitTicks(1)
just spent an hour wasting my time trying to figure out why my itemstack wasn't saving a dynmic property i was setting
then i remembered i can't directly modify itemstacks
because i have to set the item each time this actually sucks...
ContainerSlot dynamic property
maybe
litteraly no difference from just using setItem
its no good for my use case
it directly reference to the slot
so all changes is automatically applied to that item
yeah
but that doesn't help me
i am trying to store a timer value
basically it makes the item unusable and it it constantly plays that animation when you collect an item
no good for me
Then use the cooldown component
the timer is for a sound
not using the item
i'm just going to store on the entity because i don't see another good simple way
store it on the player
yeah thats what im saying
Once again, what's the problem?
hm?
do you need to store a dynamic property in an item?
yes
but it will constantly modify the value of that property which i realized is bad
because it will make the item unusable
and trigger some stupid pick up animation
dynamic properties of items work only if its maximum quantity is 1
Do you need to change the property every tick?
it's a timer
so yes
it just stores a timer value
but what ever, i am just going to store it on the entity who has the item
why do you need to change the timer every tick? its nameTag will be visible and there will be something like "05:11"?
because i want it to be like that
wouldn't it be better for you to use the actionbar?
?
for example, when you take an item in your hand, you are shown "05:11" using the actionbar, and in the item itself, only the start time in ticks is stored.
i play a sound and set the timer to 50 if the timer is 0
then tick down every tick
i don't know what action bar has to do with this
Why do you need to change the item every tick?
i was storing the timer there for item specific timers
but i found issues with that
and for my use case its not super needed
if items in the inventory had a unique runtime ids i could probably handle this in a map or something but what ever to give each one a unique timer
since this information only needs to persist per session
you need to pick up the timer and it would show you the time, and for this you want to use the nameTag of the item. I suggest you write the current game tick there at the very beginning of the timer's operation and when you pick it up, the time is displayed to you through the actionbar (according to the formula: system.currentTick - the recorded tick)
what does it matter if it won't be per unique instance of that item
On game start:
item.setDynamicProperty("startTick", system.currentTick)
let tick = item.getDynamicProperty("startTick")
player.onScreenDisplay.setActionbar("Time: " + (system.currentTick - tick))
oh i see
I don't understand you
What is a "unique copy" of an item?
so why is it needed?
its irrelevant
i already realized i don't want to store any on the item
in this case a timer for playing some sound
because of this
it does. I offer you a normal code for implementing a timer, and you tell me that it is "somehow" not unique
Well then think for yourself
How do i get the current slot id and save it so i can set an item with setEquipment there later?
where to get Minecraft Bedrock Edition actual entities.json? Not outdated
will structure voids be removed?
wdym
guys
is there a way to lock item inside chest?
It can still be moved from chest to player inventory
I know this is not a question for this branch but is netherite hard to find or make in Minecraft cause I made a difficult game and I want to consider the use of netherite in crafting recipe
I never played survival on Minecraft since they released netherite armor so I don't really know
/clear and add back the item :3
@deep plank check dm
How do i get the current slot id and save it so i can set an item with setEquipment there later?
player.selectedSlotIndex returns one number from 0 to 8
And when i do define a variable to that and just insert the variable when i replace my item , it would replace the item in the slot when the variable was defined?
while and for loops are the worst
haven't worked with them in a long long time
it's basically recursion but worse
?
while and for loops are dumb
actually for loops (when it is use to repeat thing n times) is fine
What?
get:
const item = player.getComponent("inventory").container.getItem(player.selectedSlotIndex)
set:
player.getComponent("inventory").container.setItem(ItemStack, player.selectedSlotIndex)
with recursion you can actually use it to structure and name your code but while loops in particular just make every more nested for basically no reason
That is a complaint sure
The issue is that its set after the slot switched
yeah I'm complaining because I have to use them
actually no, I'm just using them because I just want to have the knowledge of how to use them effectively just in case
if you do all in the same tick it wont, if you arent doing it in the same tick then save the slot in a map.
So i save slot by
let map1 = new Map()
map1.set(player, player.selectedSlotIndex```
yeah, doing:
const slotI = map1.get(player) // will return the slot
but the map should be defined out of the run or the function that gets repeated
Ah ye, but its all inside one function so i wouldnt even need the map i think
Its basically the function and inside the timed command
We use var for variables which shouldnt auto redefine themselves right?
maps are useful to save data to objects, doing const slot will break the code if there are more than 1 player
Function is specifically ran by the player
didnt you said it was in different ticks?
Maybe i still use map than
Yes but inside the function
Its an run interval
*system.run
ok
depend i didnt see your code yet
Its kinda to long to send all but wait
huh someone using Map. haven't seen that in awhile
thats the most useful thing in the world
how would you add something to it?
map[key] = somethingElse
console.log(map[key]) //logs somethingElse
yeah you add the new key in it
yeah but Map class has a lot of other thinsg
The biggest reason for me is that you can use objects as keys for Map. And the performance is slightly better
valid
for handling multiple players you just do:
map.set(player, value)
also I read, it also have a bunch of other benefits and also more descriptive for types
very cool
you have convinced me
looks a little dangerous with apis tho but for Minecraft is kind of cool
can scripts access scores on entities other than players?
yes
How to decrease the stacked item in an entity's inventory?
So currently I am trying to program that the Item called lb:paper_clip can open a thing called lb:loot_box in like a few chances and every chance used removes 1 paper clip from the inventory and when opened the loot box the loot box changes block states and for some reason this code I am working doesn't do shit
const PAPER_CLIP_ID = "lb:paper_clip";
world.beforeEvents.itemUseOn.subscribe(event => {
const player = event.source;
const blockLocation = event.block.location
const block = player.dimension.getBlock(blockLocation)
if (block && block.typeId === LOOT_BOX_ID) {
const inventory = player.getComponent("minecraft:inventory").typeId
const heldItem = inventory
if (heldItem === PAPER_CLIP_ID) {
player.getComponent("minecraft:inventory").container.removeItem(heldItem);
if (Math.random() < 0.5) { // 50% chance to open
const newBlockState = block.setPermutation(
Blocks.get(LOOT_BOX_ID).createDefaultBlockPermutation().withState("lb:opened", true)
);
player.dimension.runCommand(`setblock ${blockLocation.x} ${blockLocation.y} ${blockLocation.z} ${LOOT_BOX_ID} [opened=true]`);
player.sendMessage("The loot box has been opened!");
} else {
player.dimension.runCommand(`particle minecraft:happy_villager ${blockLocation.x} ${blockLocation.y} ${blockLocation.z}`);
player.sendMessage("The paper clip didn't work. Try again!");
}
} else {
player.sendMessage("You need a paper clip to open the loot box.");
}
}
})```
any errors?
Idk what errors you're getting, but this part definitely doesn't seem intentional
the inventory itself doesn't have a type Id
and you aren't getting the held item anywhere
tbf, you don't need to get the item from the inventory at all. This event comes with the itemStack of the item being used already
.getComponent("inventory").entity
.getComponent("inventory").containerType
i think he may be trying to do one of those
he's not trying to do either of those

import { world, BlockPermutation } from "@minecraft/server";
const LOOT_BOX_ID = "lb:loot_box";
const PAPER_CLIP_ID = "lb:paper_clip";
world.beforeEvents.itemUseOn.subscribe(async event => {
const player = event.source;
const block = event.block
if (block.typeId === LOOT_BOX_ID) {
const heldItem = event.itemStack
if (heldItem.typeId === PAPER_CLIP_ID) {
await (event.itemStack = null);
if (Math.random() < 0.5) { // 50% chance to open
block.setPermutation(
BlockPermutation.resolve(LOOT_BOX_ID).withState("lb:opened", true)
);
player.sendMessage("The loot box has been opened!");
} else {
player.dimension.runCommand(`particle minecraft:happy_villager ${block.x + 0.5} ${block.y + 0.5} ${block.z + 0.5}`);
player.sendMessage("The paper worked. Congratulations!");
}
} else {
player.sendMessage("You need a paper clip to open the loot box.");
}
}
})```@terse spindle
tysm
what the
we need a pickup time property in EntityItemComponent 😦
wait the block isn't changing states and it isn't sending the player messages
is there a way to call a const into a runcommand method?
template literals
how can i select any of the block ids in an array?
in other words, if the objects in the main hand match any of the objects in a constant array, run this. How can i make it detect for any of the items in that array?
im making a custom bow using scripting
is it possible to make the projectile (in this case an arrow) not hurt me when I initially shoot it?
the arrows the vanilla bow shoots will never hurt me
even if they spawn behind my head or in my body depending on rotation
cant you make one with items json?
yes but i don't want to use that
would be easier to do it with item jsons tbh
well, try setting the projectile owner
good idea
ok that worked
also im not using the shooter component because i don't want to be restricted by what ever it has
i already have the base logic for my bow done either way
how do i make an item decrement stack after being placed with scripts
50% chance...
?
Wdym by "being placed with scripts"
my block is placed and the rotations are managed through a script event, but when its placed it automatically sets back to the number it was already at
itll disappear for a moment but then reappear in my hand
itll still place though
Aight, make a post abt it 
I spammed it….
I'm trying to play the bow animation with player.playAnimation but it only lasts for a frame
but if it call it constantly it makes the player flicker
any ideas?
oof, mb. the itemstack there wasnt assignable
world.beforeEvents.itemUseOn.subscribe(async event => {
const player = event.source;
const block = event.block
if (block.typeId === LOOT_BOX_ID) {
const heldItem = event.itemStack
if (heldItem.typeId === PAPER_CLIP_ID) {
await null;
if (heldItem.amount === 1) player.getComponent("equippable").setEquipment("Mainhand")
else {
heldItem.amount--
player.getComponent("equippable").setEquipment("Mainhand", heldItem)
}
if (Math.random() < 0.5) { // 50% chance to open
block.setPermutation(
BlockPermutation.resolve(LOOT_BOX_ID).withState("lb:opened", true)
);
player.sendMessage("The loot box has been opened!");
} else {
player.dimension.runCommand(`particle minecraft:happy_villager ${block.x + 0.5} ${block.y + 0.5} ${block.z + 0.5}`);
player.sendMessage("The paper didn't work. Try again!");
}
} else {
player.sendMessage("You need a paper clip to open the loot box.");
}
}
})
player.getComponent("equippable").setEquipment("Mainhand",
heldItem.amount === 1 ? undefined : heldItem.amount-- && heldItem
)
why?
thanks
cus we're only allowed to look, for the most part ;-;
wait it didn't say that it was read only
exactly where...
😠
Any freelance devs?
mb, i didnt mean to upset u
but for the most part, changing an (entity, block, item, etc.)'s identity to exist during a beforeEvent isn't likely an option, so most part is moved onto the followed gametick to occur via system.run
sigh
finally got my mock of the hopcroft karp (very wacky name) algorithm implemented
with my weird way of storing data done
I feel like I'm dying
ty, I probably need that lol
how can I reach DynamicProperties for my minecraft world? Are there any software?
I think it is stored in the level.dat
not sure where tho but you can probably ctrl-f in there
to find it
wdym "reach"
u wana edit that by...
idk if anyone tried editing that specific data via raw world/db files,
but the UUID is the BP uuid that can change it with scripts
yeah I would reckon
I want to see variables that stored in dynamicproperties actually
I tried to use debugger but it wasn't work for me,
I want to see the variables that I will save with the script
world.sendMessage, console.warn, log...
if that BP uuid is in one of ur BPs then u can reveal it
I want access my package's dynamicProperties, this screenshot is from Universal Minecraft Editor but it is paid,
oh then you can't just log the thing?
I thought I was another pack dynamic props
oh thanks
in manifest.json, use that uuid
then in scripts/main.js
import { world } from "@minecraft/server"
const props = world.getDynamicPropertyIds()
console.warn(JSON.stringify(props))
console.warn(JSON.stringify(props.reduce((a, property) => {
a[property] = world.getDynamicProperty(property)
return a
}, {})))
afaik, the dynamic properties are attached exclusively to bp uuid
and this actually proves it
How to disable player fly?
/ability @s myfly false
But player is not falling after disabling the ability
I need to make player fall if he flying and ability got disabled
change gamemode?
how do I get entity id? I have the following target but when I try to const targetId = target.Id I'm getting undefined.
const targets = player.dimension.getEntities({
type: "eduelfie:home",
scoreOptions: [{ objective: 'home', maxScore: s, minScore: s }]
});
const target = targets[0];
Id or id?
oh let me check
ThankYOU. I've been beating my head against this trying to figure out what I did wrong!
can I edit the button text on a modalform and if so, what is the syntax?
The submit button?
yea, is it possible to change the submit button?
is it possible to chnage player model?
there must be some way to do it because I've seen morf mods.
yes
.submitButton("text")
Thank you
np
is there way to access an entity's ticks since alive value?
unfortunately, that didn't work. I'm still in server-ui 1.1.0
use 1.3.0
how can I make a sound play 1 block in front of me
Player.dimension.playSound
________________________
How can I spawn particles in an unloaded chunk via script?
It is possible with runCommand but it doesn't work as I need
you can't
why would you want to do this anyways
no one will see it
The particles are rendered very very far away, so I can use player.spawnParticle to show the particle only to this player, however it can't if the area isn't loaded, I could use tickinarea
That still won't show it for the player
Your best bet is making something that will always be visible to the player
And move towards that marker as they get closer to it
I know it shows it because I've tried it before, I'm just looking for it to load in a unloaded chunk
Is there a way to cancel fall damage for a specific player
add tag and use player.json to cancel fall damage for that specific tag
whats the latest version of MC?
Load in a ticking area, play the sound, unload
There is no native way to load the chunk right? Do you think the best way would be to use an entity to load the chunk to avoid using tickinarea and then kill it?
well to spawn an entity there it has to be loaded..
so at the end of the day ur still using a ticking area
Not with runCommand, However, entities that use tick are not listed in the tickinarea, which would make the system continue to function regardless of whether the limit of tickinarea has already been reached in the world.
is there a 50 file limit for scripting?
for some reason the moment i made the 51st file, that file didnt register
nvm, just the worst brain fart a man could have
relatable
i cant even understand a single line of code of this
me too my friend lol
doesnt seem the code to be related with script api
is it
no but it is barely Minecraft related
it's for turning an image into fill commands
using the least amount of fills
Where is the best place to report script api bugs?
TIL break/continue in JS supports labels. I've seen them in other languages like Rust.
How do i do that in player.json
"minecraft:damage_sensor": {
"triggers": [
{
"on_damage": {
"filters": [
{
"all_of": [
{
"test": "has_tag",
"value": "no_fall_damage"
},
{
"test": "has_damage",
"value": "fall"
}
]
}
]
},
"deals_damage": false
}
]
},
Is it same with setEquipment?
Anyone here
?
Plz help for code
I just wanna ask a question
import { system, world } from "@minecraft/server";
system.runInterval(() => {
for (const player of world.getPlayers()) {
const health = player.getComponent("minecraft:health");
if (health) {
const ls = "▎".repeat(currentHealth);
const rs = "▎".repeat(maxHealth - currentHealth);
player.nameTag = `§l§d${player.name}\n§l§a${ls}§c${rs}`;
}
}
});
Does this code will display visual health on player?
This is the code I rewrote using Jaylay API to make it more visual
But I'm not sure if it will work because the debugger is offline.
Why don't you try it out in the game?
this works ONLY FOR PLAYERS
//set: void, sets the ItemStack to a eq slot
player.getComponent("equippable").setEquipment("equipment slot", ItemStack);
//get: ItemStack
const item = player.getComponent("equippable").getEquipment("eqipment slot");
Now I changed it
import { system, world } from "@minecraft/server";
system.runInterval(() => {
for (const player of world.getPlayers()) {
const health = player.getComponent("minecraft:health");
if (health) {
const ls = "▎".repeat(health.currentHealth);
const rs = "▎".repeat(health.defaultValue - health.currentValue);
player.nameTag = `§l§d${player.name}\n§l§a${ls}+§c${rs}`;
}
}
});
Is this correct?
world.afterEvents.itemCompleteUse.subscribe(e => {
const { itemStack, source } = e
const food = itemStack.getComponent("food")
if (!food) return;
console.warn("eat")
})
what am i doing wrong getting food component returns undefined
Well, it's simple here. Mojang is a company that makes APIs and then makes things that require these APIs through some of their own methods, with items, blocks, entities and everything else the same. Vanilla items don't actually have a food component.
oh wait
arent vanilla food items data driven?
I tried to make code execution when a person eats, but it didn't work with vanilla items (it was version 1.21.2). Apparently it's still like that now. If you look at the original "addon" mine, there will be either ancient json or there won't be any at all. From this we can conclude that everything works differently in vanilla
hmmmmm
I have long been familiar with their love to do everything, but half through json and the other half through c++
player.nameTag = "smth else"
How would u detect block broken not by player but an entity or a explosion?
world.afterEvents.explosion.subscribe
Thanks alot, appreciate that
i want to make my block do stuff so long as it exists, do i use world after events or...
You can use custom components and ticking
I remember the "tick" component is disabled after a restart or moving away from the block and in order for it to work you need to install the block again
never had this issue
I could easily make a better combat if I had a script that got the damage of a held item.
Anybody got any leads? Like, at all?
not yet, not directly from the itemStack anyway.
Damn, woulda had that addon working in like an hour
maybe you could use the entityHurt world event and detect the damage?
set a dynamic property on the item of what that damage value is maybe
|| competitors... ||
damage depends not only on the item, but also on enchantment, crit, armor and much more
yeah.
right.
they just need to add the item damage component class in the api.
It's too simple.. For example, I just redid the entire armor and damage system)
and maybe someone will think of this... but it’s unlikely that the second feature I came up with)
it would make sense for it to be added.
There HAS to be a way to do this.
.
😀
🙏
I intended for that to look terrifying but eh
So what does it do?
In short, either redo the damage system or do without it
Hell I’m fine with that.

Not my first rodeo with the damage system.
In Minecraft, armor is limited to 20 and then it doesn’t work very well. In my system it has an unlimited value and the damage is also affected by the type of damage and I’m thinking of adding a couple more dependencies
Theoretically, does that mean I could get the damage of any held item, given an event takes place or a system interval is ran?
Well, you can try to use the gametest module, spawn a simulated player there, give him a sword in his hands and make a blow from his face, then add the damage to the dynamic property of the world
🦅 I will come back to this, I am interested
that works but it spams the messages and everytime I try a chance it opens it anyways and takes like 4 paperclips out instead of 1
do you play on PC?
and I also wanna make it to where it doesn't work on loot boxes that are already open but for some reason it just does it
yeah ofc
The mega ingenious corporation Mojang made one bug in which clicking on a block with the mouse counts several times. You need to create a variable in which the click tick is recorded, and if the tick coincides with the current one, then do not execute the code
I have a function for this..
let denyMap = {}
function deny(player, cause) {
let data = denyMap[player.name] || {}
if (cause == "all") {
data.every = system.currentTick + 1
} else {
if (data.every >= system.currentTick) return true
if (data[cause] >= system.currentTick) return true
data[cause] = system.currentTick + 1
}
denyMap[player.name] = data
}```
it should be used like this:
if (deny(player, "lootChestOpen")) return
// Code here
Oh, I see, gotcha
Ye
it returns true if this player had an event with such a reason in the next 2 ticks
Ah
|| There are so many hidden bugs in this industry, the fixes for which are found in some roundabout way... it feels so strange ||
tysm
erm, how do i make custom commands
chatSend beforeEvents
Documentation for @minecraft/server
why not after events, is there a difference
yes.
in before Events, you can cancel the event.
this is good in custom commands because you can cancel the message from sending.
okay, but how do i set it up, is there an example
how you would setup any script
theres an example from here
thanks
world.beforeEvents.chatSend.subscribe((event)=>{
const {message, sender, targets} = event
if(message == "!hello"){
sender.sendMessage("hi")
event.cancel = true
}
})
[Scripting][error]-Unhandled promise rejection: TypeError: cannot read property 'subscribe' of undefined
[Scripting][error]-Unhandled promise rejection: TypeError: cannot read property 'subscribe' of undefined
[Scripting][error]-Plugin [Superhero Plus - 1.0.0] - [main.js] ran with error: [TypeError: cannot read property 'subscribe' of undefined at <anonymous> (commands.js:3)
]
Why is it doing this
Chat event is beta scripts only
why?
Because it's not stable...?
welp, so much for not using experiments
It's not a bug, but you also don't need to do all that anymore
the before event has a property isFirstEvent that was added recently
Anyway to do 2D graphics at runtime? With a map? Particle effects?
How am I to test who own world
this appeared literally a few hours ago. The function is still not bad, but I will still use my method because I need it that way
how to get entity fieldofview(angle) ?
entity.getViewDirection()
is it possible to, upon clicking on a block, spawn an entity at that block's position then automatically make the player who clicked on it a rider of that entity?
when event, spawnEntity and then addRider via rideable component
Thanks bro
what happened to getRedstonePower for blocks, its still referenced in examples in the server module but it seems to been removed in 1.14.0
it was not removed in 1.14.0, it was just added only in 1.16.0-beta
When the debugger will fix?
I have no idea why I never asked this, but what alternatives can be used to extend the Player class? Because since it's a private class, it cannot be extended.
it is not?
Of course not. Its constructor is private.
I've been extending the Player class in nearly every addon I make
It's definitely possible
(I'm using a work computer, so I can't download anything. This is purely for scripting practice and development planning. I'm just on my lunch break.)
just import player class and extended it as you like
You can use Object.defineProperties on Player.prototype
And just assign methods to the prototype as well
But what if I need to have an API for something like character creation for a player? Such as their RP name, age, species, faction, element, etc.
I think it's best to use the player ID property then
Since it's totally unique
Just store it as a private property in your class
I have honestly never heard of Object.defineProperties nor Player.prototype before.
That would be for adding new properties and methods to the player class
I think I misunderstood your goal
But then again, if it's a server (which is what I'm planning), then it's going to be difficult for me to figure out how to make this work without a way to extend the Player class.
I'm planning on making a server that's kinda like an Origins-esque MMORPG-style server.
Just use this and I believe it'll achieve the same result. You can just call world.getEntity on the ID to get the specific instance you want
I...
I have a basic JavaScript/TypeScript understanding, but I have no idea how someone could use the player ID property.
I'm trying to learn how classes work, but I have no idea how to use the player ID in the class, let alone the two methods you mentioned earlier.
you need data to persist past reload?
because making a new class won't help you with that
Then again, I don't want to create an entire script file which only consists of functions that constantly ask for the specific player target.
use dynamic properties
I'm doing that. It's just the repetitiveness of the functions for getting and setting those dynamic properties that I have an issue with.
ive been looking and I can't seem to find what event i would use to detect when the player clicks on the block
is there any way to get the item thats being placed in playerPlaceBlock after or before events?
i tried with before event .getItemStack and it gives me an item with no data.
using permutationBeingPlaced
You'll need to store it in an array with the current blockID/attributed tag and the associated item Id
oh wait
have you tried using itemUseOn?
nope
but i just discovered i can get the itemstack by using equippable component in the before event lmao
it makes sense
ahh, yeah
since its a before event its still in your hand, its not placed
i got it working lucklily
thanks for trying tho
❤️
idk how i didnt think about that before lol
script to put a block in the offhand slot?
im not upset lol it's just my reaction to the breakBlockBeforeEvent
I'm friends with someone that is on mobile, they use bridge.
its possible to detect when a player is operator?
import { world, EquipmentSlot } from "@minecraft/server";
world.afterEvents.itemUseOn.subscribe((event) => {
const player = event.source;
const blockHit = event.block; // Access the block hit from event
const mainHandItem = player.getComponent("minecraft:equippable").getEquipmentSlot(EquipmentSlot.Mainhand);
// Check if the item in the main hand is a lodestone compass
if (mainHandItem && mainHandItem.typeId === "minecraft:lodestone_compass") {
// Check if the block hit is a lodestone block
if (blockHit && blockHit.typeId === "minecraft:lodestone") {
// Get coordinates of the lodestone block
const x = Math.floor(blockHit.location.x);
const y = Math.floor(blockHit.location.y);
const z = Math.floor(blockHit.location.z);
const lodestoneCoords = `Lodestone: ${x} ${y} ${z}`;
// Set the new lore on the lodestone compass
let currentLore = mainHandItem.getLore();
currentLore.push(lodestoneCoords);
mainHandItem.setLore(currentLore);
// Update the inventory to reflect the new lore without deleting the item
const inventory = player.getComponent("minecraft:inventory").container;
inventory.setItem(player.selectedSlotIndex, mainHandItem);
// Inform the player that the lore has been set
player.onScreenDisplay.setActionBar("Lore set on lodestone compass!");
}
}
});```
Why is this deleting my item?!!
You shouldn't need to set the item from the inventory.setItem call since you've already been modifying it with the containerSlot instance.
Gotcha. Thanks
It works! Thank you!
It was getting on my nerves lmao, the very thing I set to prevent that happening was causing it to remove the item.
Anyway to make something like backup respawn points with spawn protection ?
like you can set multiple spawn points (like by right clicking on bed) and if one bed is broken then the sevond spawn point is used ?
And there is a 5x5 area around the spawn point where there is spawn protection (using runcommandasync)
if anyone can help pls ping me ?
huh I wonder
do you guys test your BP?
with like gametest
but tbh I don't feel like many people here test anything lol
hello
hello
quick question is the before events of the playerInteractWithBlock still only works in beta version of script?
gametest is actually just for checking whether the condition has passed in a structure
also yeah i do test BPs, cuz it would fall apart if i dont

yeah that's what tests are
i mean in a structure
oh sorry let me check rq
i mean who don't test his/her addon?
by test, I mean like actual unit e2e testing.
98% in mcpedl
thank you... i'm pretty lazy opening my mc
like what they do at mojang
BRUH... i can't go on making script without testing it. im not that confident with my work lmao
yeah thats good
but im saying 98% of people in mcpedl dont test their addon at all
not only scripts but everyting lmao
theyre not even aware of content logs
like when i download an addon from there
and test it with content logs on
off been awhile since i touch dicsord i didn't notice the forward button
same tbh but it annoys me so much when there's conent log
then i'll fix it myself
just bumping this.
ye iirc
according to Microsoft's script API docs, it isn't
but it is somehow
its just not labelled as beta
man that sucks.... looks like i need to use itemUseOn
well it p much does the same so
I think y'all don't understand what I mean by "tests"
welp ig not
what?
i mean the way it functions
ohh you meant by p is 'pretty' much? im sloww
i get cringed with my bio lmao
how to check if message is equal to not startsWith?
if (message.startsWith("-ad")) {
try adding !
if (!message.startsWith("-ad")) {}
startsWith returns boolean
you can check if it equals false or just use the NOT operator (what coddy is suggesting)
not working
so it’s impossible to detect messages that equal to command?
?
nvm I found out how to do it
let staff = world.scoreboard.getObjective(`staff`).getScore(player)
whats the issue?
Im dumb
const obj = getObj(o) ?? addObj(o)
If you have any specifc questions related to JS as a language then ping me 4 times in the row
This is OverTakes method that does a prototype manipulation
wow that's something
How can I set the mainhand item from a custom entity? entity.getComponent(Minecraft.EntityComponentTypes.Equippable) returns undefined
well pre-increment and after increment has different usages, also i += 1; its expression return should not be usaded
they basically all does the same thing (unless you're using them in expression which you aren't supposed to do anyways)
so there's no case where you need to use them instead of the others
not really, pre-increment, increments first and returns later, after-increment, returns current value and after that increments variable value
yes I know, but why are you incrementing in a expression
couldn't you spare just one line?
i don't understand
sorry I'm a little tired
so my point is, you shouldn't modify a variable inside another expression
depending on its result
¯_(ツ)_/¯
wait does really some one uses the space between the (i and ++)
yes I do makes the variable name a little bit clearer
Doesn't feels like JS developer lmao
you have to be 100% typescript guy, fr
JS is not build to be clean and readable
ig but js isn't build for server and someone have to make node js
as a wise man said, "the only use case for JavaScript is to build thing that it isn't supposed to"
ya, JS is incredible language but pain to manage your projects in
thats why somany sites are actually running generated JS not written by man
(fyi. yes, I does use ts because I can't stand js anymore)
but JS is actually very interesting language after all, its just crazy what things you can do, and it actually creates new programming concepts cus its just another language that you can't compare to others
yeah it's one of the most used programming languages today after all.
Well JS really small languages and there is no much to talk about, the big book looks like whole ECMAScript specification
lmao
hi guys, sorry for interupting
how do i detect an entity's target?
not sure bu i think there is a target property on entity
huh? wdym by targeting
you know, zombie hates players, then it sees them it wants to kill them
how do i detect if the zombie saw a player and wants to killl it?
i tried it but it gives me "undefined"
I'm not sure but I think you can't because performace
i think you didn't understand
look, the warden has multiple targets(players,zombies etc), how do i detect if the warden wants to kill a player not any other mob
it return undefined if there is no target
oh, does it mean i'm firing it too early?
I am using world.afterEvents.dataDrivenEntityTrigger
hmm
send your code
world.afterEvents.dataDrivenEntityTrigger.subscribe((event)=>{
let mob = event.entity;
switch(event.eventId){
case("bd:roar"):{
if(mob.typeId.startsWith("secret:noneofyourbusiness")){
mob.runCommandAsync('/tag ' + mob.target +' add bd:chased')
console.warn(mob.target)
}
};
}
})
||@distant tulip ||
it returns undefined
on target acquired
do i use timeout?
try
ok going to try it rq
but you can just use filters property on "minecraft:on_target_acquired" component
and how is that going to help me?
timeout didn't work
filter out players?
how to use module server admin
dont crosspost, and it looks like you already got an answer
https://discord.com/channels/523663022053392405/1294676391203311637
dimensions.forEach(d => {
let dims = world.getDimension(d);
items = dims.getEntities({ type: "minecraft:item" });
})
items.forEach(itemEntity => {
const itemComponent = itemEntity.getComponent("item");
let itemId = itemComponent.itemStack.typeId;
itemId.startsWith("minecraft:") ? itemId.slice(10); : false;
Why is this not work?
Is not removing Minecraft: from item
You are slicing it properly, but nothing is being done with the result. forEach simply calls a function on every entry in the array, and does not return anything.
Sounds like you want items.map()
const flatItems = items.map(itemEntity => {
const itemComponent = itemEntity.getComponent("item");
let itemId = itemComponent.itemStack.typeId;
return itemId.startsWith("minecraft") ? itemId.slice(10) : itemId;
});
Then you act on flatItems. It's worth noting that you cannot (or at least, should not be trying to) change the actual item IDs onto the item entities like that. At best it won't do anything productive
Thank you :)
Ohh, ok
ohhh, sorry i didn't clarify
it's nessecary for all targets becuase he plays a roar animation when he detects a target
How am I detect if entity is on fire
getComponent('minecraft:onfire')
Why might I be getting this error upon adding .setRotation()? It wasn't doing this before I added it
initEvent.blockComponentRegistry.registerCustomComponent("custom:block", {
onPlayerInteract: (event) => {
const { player, block, dimension, face, faceLocation } = event;
const miniBlockEntitySpawn = {
x: block.center().x,
y: block.center().y-0.4,
z: block.center().z
};
const blockEntity = block.dimension.spawnEntity("sci:block_mount", miniBlockEntitySpawn).setRotation(player.getRotation());
blockEntity.getComponent('rideable').addRider(player);
}
})
});```
`[Scripting][error]-TypeError: cannot read property 'getComponent' of undefined at <anonymous> (main.js:360)`
because setRotation returns void
you need to move it to be separate
like blockEntity.setRotation
Guys, I once again ask how do I detect an entity's target?
world.afterEvents.dataDrivenEntityTrigger.subscribe((event)=>{
let mob = event.entity;
switch(event.eventId){
case("bd:roar"):{
if(mob.typeId.startsWith("secret:noneofyourbusiness")){
mob.runCommandAsync('/tag ' + mob.target +' add bd:chased')
console.warn(mob.target)
}
};
}
})
I tried .target but it didn't work
it prints undefined
seem to be bugged
is it possible to execute GET requests to get some data from a website?
how could I obtain blockFace data in a custom block component?
initEvent.blockComponentRegistry.registerCustomComponent("sci:mBMountSpawn", {
onPlayerInteract: (event) => {
const { player, block } = event;
const blockFace = data.blockFace;
}
}
});
});```
i need the direction to summon a specific entity depending on that direction
data?
yeah, like world.beforeEvents.itemUse.subscribe(async function (data) { allows for data.blockFace
apologies for the incorrect terminology
you did get it
const blockFace = data.blockFace;
in this one yes
but in the first snippet i can't call data
as a parameter
use event not data
I'm working in education so version is still 1.21.05 and working in stable server ui is only 1.1.0 as far as I know.
its still not calling this though https://jaylydev.github.io/scriptapi-docs/1.21.31/classes/_minecraft_server_1_14_0.ItemUseOnEvent.html#blockFace
try 1.2.0-beta then
.submitButton either got added to 1.2.0 or 1.30
pretty sure it was 1.3.0
then he cant use since he on 1.21.05
🤷♂️
json ui still exists..
it dose...
On vscode though it says it's giving "any" as opposed to this which gives "Direction"
try event.face
do you remember what version server-ui was in back in march
nope
me neither, but thats when .submitButton got added to preview
@copper lake if submitButton doesnt work for you, make an rp with a folder called "ui" inside. then add this file.
if you change the source property name for both long forms to your form title it should be a custom submit button for that form.
@thin steeple working with stable because the average teacher isn't able to access experimental toggles on school managed devices.
alr
For those of you familiar with translation & RawMessage, how are you supposed to build a message such as this using RawMessages?
this.description and helpEntry.description are both RawMessage types in this example.
toRawMessage() {
let output = `§2${this.command.getUsage()}§8 - ${this.description}`;
for (let helpEntry of this.command.getHelpEntries()) {
output += `\n §7> §2${Command.prefix}${helpEntry.usage} §8- ${helpEntry.description}`;
}
return output;
}
anyone know if its possible to delete a dynamic property?
i have unused ones on a player i wanna remove and there's not really a method
try setting them to undefined
alr
Bridge is hard to use on mobile
🤷♂️
is it possible to do block-display entities?
maybe I am using an outdated script for .target?
since when .target was added?
function replaceItems(player) {
if (!player.isValid()) return;
try {
const replaceableItems = ["minecraft:torch", "minecraft:soul_torch", "minecraft:lantern", "minecraft:soul_lantern"];
const customItems = {
"minecraft:torch": "evo:torch",
"minecraft:soul_torch": "evo:soul_torch",
"minecraft:lantern": "evo:lantern",
"minecraft:soul_lantern": "evo:soul_lantern"
};
const inventoryComponent = player.getComponent("minecraft:inventory");
if (!inventoryComponent) return;
const inventory = inventoryComponent.container;
for (let i = 0; i < inventory.size; i++) {
let itemStack = inventory.getItem(i);
if (itemStack && replaceableItems.includes(itemStack.typeId)) {
let newItemId = customItems[itemStack.typeId];
if (newItemId) {
let newItemStack = new ItemStack(newItemId, itemStack.amount);
inventory.setItem(i, newItemStack);
}
}
}
} catch (error) {
console.warn("Error:", error);
}
}
This crash game, please help
When I drop the items, my game close
Here is video showing. When the other testing account drop torch it crash game immediately
Only for that account though
[Scripting][error]-TypeError: cannot read property 'container' of undefined at replaceItems (index.js:95)
at <anonymous> (index.js:142)
at forEach (native)
at <anonymous> (index.js:143)
That is error
Please somebody help
is it possible to make entities undespawnable with script?
How can I set the item type from an item entity?
how to get all entites in a specific radius from the player (not commands like i need to get entity variable)
/docs info...?
ohh thx
ohhh, i was using it in the #bot-usage
the command isn't usable there
the bot is unavailable in #bot-usage




