#Script API General
1 messages · Page 72 of 1
that it!
I will try to solve this
nvm, finnafinest's message is literally all the code does
Bloating at it's finest.
Hey @dim tusk
?
Want to try the Traveler's Titles Bedrock add-on pack I created?
'-'
If you want to try out the Traveler's Titles Bedrock add-on pack I created, I'll send you a link to the add-on in MediaFire for you to download and try out in Minecraft Bedrock.
why is event.cancel = true not working?
show your code.
just the wiki code:
world.afterEvents.chatSend.subscribe((eventData) => {
const player = eventData.sender;
switch (eventData.message) {
case "!gmc":
eventData.cancel = true;
player.runCommand("gamemode c");
break;
case "!gms":
eventData.cancel = true;
player.runCommand("gamemode s");
break;
default:
break;
}
});```
thats afterEvents
wrap it in system.run
ok
also there's a native method for changing gamemode
you dont need to use commands
player.setGameMode('creative')
and here's a doc for the beforeEvents priv system.
https://wiki.bedrock.dev/scripting/script-server#beforeevents-privilege-system
ohh thc
*thxsm
how do I make that: player target in command, ik I can do player.runCommand(`gamemode c ${target}`), the hard part is to define target
oh wait I think ik
I did
player.setGameMode("creative")
i suggested that
didn't read above
so, he just ignored what you said
he probably meant how to make another player in the world creative
possibly
.
const target = world.getPlayers({name: targetName})[0]
yoo thx for helping me but I have a question how do make a wait function that works mit system.run
thats working too
umm I think
whats wrong with using the native method?
lol
What can we do with pfid, given in the player join event?
I’ve searched a bit online and haven’t found any way to gather meaningful information from it
nothing... sense it is spoof-able
some servers do use it to identify the player but that is not a good idea
:(
Could I have help with fixing this script
import { world, system } from '@minecraft/server';
function getEntityAge(entity) {
//const spawnTick = entity.getDynamicProperty('spawnTime');
//return system.currentTick - spawnTick;
const spawnTime = entity.getDynamicProperty('spawnTime');
return Date.now() - spawnTime;
}
system.runInterval(() => {
for (const player of world.getPlayers()) {
const hand = player.getComponent("equippable")
if (player.hasTag("electric") && player.hasTag("fly")) {
const playerLoc = player.location
const vel = player.getVelocity();
if (vel.x !== 0 || vel.y !== 0 || vel.z !== 0) {
const trail = player.dimension.spawnEntity('ltng:trail', playerLoc);
trail.setDynamicProperty("spawnTime", Date.now());
world.afterEvents.entitySpawn.subscribe((event) => {
if (event.entity.typeId == 'ltng:trail') {
const age = getEntityAge(trail)
const playerRot = player.getRotation();
const maxAge = 0.05;
if (age <= maxAge) {
trail.setRotation({ x: playerRot.x, y: playerRot.y });
}
}
});
}
}
}
});
The problem is in the function
what need to be fixed?
error
?
does it throw errors?
Yes
what error
I haven't set the spawn time dynamic property to a value
And don't know what value to use
Wait nevermind I mistook the error
The content log says that it was "unable to call function getDynamicProperty at line 7 and line 22"
hi
1.18 is now final right?
Yes it's stable
await system.waitTicks()
is this normal?7
ik i need the value
import { openUIBuilderMenu } from "../main.js"
import { wait } from "../functions/wait.js"
world.beforeEvents.chatSend.subscribe((eventData) => {
const player = eventData.sender;
switch (eventData.message) {
case `!gmc ${player.nameTag}`:
eventData.cancel = true;
system.run(() => {
player.runCommand(`gamemode c ${player.nameTag}`);
});
break;
case `!gms ${player.nameTag}`:
eventData.cancel = true;
system.run(() => {
player.runCommand(`gamemode s ${player.nameTag}`);
});
break;
case `!gms`:
eventData.cancel = true;
system.run(() => {
player.runCommand(`gamemode s`);
});
break;
case `!gmc`:
eventData.cancel = true;
system.run(() => {
player.runCommand(`gamemode c`);
});
break;
case `!ui-builder`:
if (!player.hasTag("admin")) return;
eventData.cancel = true;
await system.waitTicks()
system.run(() => {
openUIBuilderMenu(player);
});
break;
default:
eventData.cancel = true;
player.sendMessage(`§cUnknown command. Please use !help for a list of commands.`);
break;
}
});
world.beforeEvents.chatSend.subscribe(async (eventData) => {
and then wherever you want to use waitTIcks()
thx
Anyone know if the newest hotfix fixes the desync?
uh elaborate, didnt quite understand
In 1.21.70, there was really bad desync with clients, especially with knockback
And I was wondering if it got fixed with the newest update
Okay, i see, i wonder too.
Because the issue also happens for me
lemme check the changelogs ig
Yeah i was like fixing my addon, i sprinted then hit the creeper 2 times, it flew away
totally drunk knockback
Good news!
Am I doing something wrong with this?
const form = new ModalFormData()
.title("Rotate Entity")
.body("Select the rotation step:")
.slider(1, 8)
.button1("Confirm")
.button2("Go Back")```
It's returning a content log error
modal forms dont have buttons
oh
u can only use
slider
textfield
dropdown
toggle
or submit button
hey in line 148 is smth wrong
const updated = JSON.parse(world.getDynamicProperty('auctions') ?? '[]');
const a = updated[index];
if (!a) return;
if (a.highestBidder === player.name) {
const inv = player.getComponent("inventory")?.container;
const playerMoneyNow = moneyObj?.getScore(player) ?? 0;
if (playerMoneyNow >= a.highestBid) {
player.runCommand(`scoreboard players remove @s money ${a.highestBid}`)
.then(() => {
try {
inv.addItem({ typeId: a.icon, amount: a.amount });
player.sendMessage(`§aYou won the auction for §6${formatItemName(a.icon)} §afor §6$${a.highestBid}!`);
} catch (err) {
player.sendMessage("§cError giving item: " + err);
}
updated.splice(index, 1);
world.setDynamicProperty('auctions', JSON.stringify(updated));
});
} else {
player.sendMessage("§cYou no longer have enough money to pay for your bid.");
}
}
}, 100); ```
```line 147 world.setDynamicProperty('auctions', JSON.stringify(updated));
line 148 });```
line 148 is wrong
cuz I changed player.runCommand(`scoreboard players remove @s money ${a.highestBid}`)
Umm, how do I get the value from the custom enums in custom commands?
world.beforeEvents.chatSend.subscribe((data) => {
try {
utilities.setTickTimeout(() => {
const allPlayers = [...world.getPlayers()]
for (const player of world.getPlayers()) {
player.nameTag = "§7[§r" + Misterank(player) + "§7]§r " + player.name + "§r"
}
}, 20)
} catch (error) {
}
})
The mistake is in this
world.beforeEvents.chatSend.subscribe((data) => {
What script version are you using
I can't understand what he is even trying to do
I'm on 1.21.70 when entering a world I get the error in the world.beforeEvents.chatSend
What I do is grab the scripts in the bedrock wiki stop that it is not updated ._.
What’s the error? What’s your script version?
Sorry I didn't send the error correctly
Yes
That error is not from that code
In manifest 2.0.0-beta
It’s saying “beforeChat” of undefined
Your code has zero mention of beforeChat
I don't have another index

This is all the index code
That’s what the error says
The game seems to think otherwise
Wait, give me a moment, send you something else
I was trying the before chat and chatSen
One I get an error and another I don't get any error but the addon doesn't work
Well, the second one doesn’t exist any more
Do you have two index.js files in the same pack? Or what’s going on there
I don't have any more index
Is that second one in a different pack, or…?
Give me a moment see something, I'm not sure, but let me find out, I believe that I know why
Nvm lol, I forgot the origin exists now.
I'll just spread the param values.
system.beforeEvents.startup.subscribe(({ customCommandRegistry }) => {
customCommandRegistry.registerEnum('coddy:team', ['Red', 'Blue', 'Green']);
customCommandRegistry.registerCommand({
name: 'coddy:multi',
description: 'A command with enum, location, and number',
permissionLevel: CommandPermissionLevel.Any,
mandatoryParameters: [
{
type: CustomCommandParamType.Enum,
name: 'coddy:team'
},
{
type: CustomCommandParamType.Location,
name: 'target_pos'
},
{
type: CustomCommandParamType.Integer,
name: 'repeat_times'
}
]
}, (origin, ...params) => {
console.error('Raw params:', JSON.stringify(params, null, 2));
});
});```
Is it now possible to know who used the custom command?
with the latest preview
read the changelog.
For quick summary in that, the origin returns the source how source returns in ScriptEvent
now we just have to wait for namespaces to be optional 😭
Unhandled promise rejection: Error: Failed to call function 'getComponent' due to the Entity being invalid (has the Entity been removed?). at <anonymous>```
on a beforeEvent playerLeave?
Im pretty sure I still have a handle on the player before they leave?
show your code
world.beforeEvents.playerLeave.subscribe(({ player }) => {
const { currentValue } = player.getComponent('health');
console.error(currentValue);
});```
world.beforeEvents.playerLeave.subscribe(async (event) => {
const playerName = event.playerName;
const player = event.player;
system.run(async () => {
await player.getComponent("inventory").container.clearAll();
});
})
Ahh you can't do that.
?
And it's player.name
this triggers before player left right? Since system.run() runs teh next tick, so teh player already left you can't clear it anymore.
so whats the fix for this?
uh
async?
Store the ID of player in a dynamic property and use playerSpawn to clear it.
@snow jungle
why not just use playerSpawn to clear inventory?
thank you for repeating it lol
depends, what if he wnat to control who will be cleared 🤷🤷
since the intention is to clear the players inventory when they join back
thats where you use dynamic property or tags i guess
-# that's why I said this.
more steps tho, since there's no built-in player property
Only playerName and playerId
whar
oh right it doesnt
playerSpawn it is then
i think you could also use WeakMap for this cuz
garbage collecting
for?
yeah I know it's Garbage collecting, but for what?
my idea is to add a WeakMap for checking if the player has joined or respawned
if the player joined (using playerSpawn event), clear inventory and set a key
if the player respawned (check if the player has key), dont clear inventory
if (!initialSpawn) return
...does initialSpawn fire if player rejoined?
Yes if the world was closed... But in server it doesn't trigger again afaik.
Since the world wasn't closed or stopped
Unlike multiplayer, local worlds or realm(?)
tags exists tho right?
mhm, but tags dont remove by its own when player leaves
what min engine version, script version and ui version are we on
const inv = player.getComponent("inventory")?.container;
const playerMoneyNow = moneyObj?.getScore(player) ?? 0;
if (playerMoneyNow >= a.highestBid) {
player.runCommand(`scoreboard players remove @s money ${a.highestBid}`)
.then(() => {
try {
inv.addItem({ typeId: a.icon, amount: a.amount });
player.sendMessage(`§aYou won the auction for §6${formatItemName(a.icon)} §afor §6$${a.highestBid}!`);
} catch (err) {
player.sendMessage("§cError giving item: " + err);
}
updated.splice(index, 1);
world.setDynamicProperty('auctions', JSON.stringify(updated));
}); // line 140
} else {
player.sendMessage("§cYou no longer have enough money to pay for your bid.");
}
}```
Is there a way to detect what item an entity is holding and run an event based on the item held?
By running an event, I mean a function that runs
/event to activate that event in an entity, if possible
Min engine version doesn't really matter tbh, but server and ui version's yes... So if stable rn it's 1.18.0 for server and 1.3.0 for ui, and for beta it's both 2.0.0-beta
Yes but it's laggy so it's not really reliable.
Awh, alright. I'll just rely on component switching using timers
Wait...
you can use functions files and check holding of item using hasitem={}
why use then? successCount already exists, 0 if failed and >= 1 if success.
Just do that.
I'll check the documents
One more question,
How I can reduce damage recieved by an entity without using resistance, even if it is coming from an override damage attack?
execute as @e[type=armor_stand,hasitem={item=diamond,location=slot.location.mainhand}] at @s run event entity @s .... ```
not possible with just scripts
Darn
Is there any resources you could point me to? If available
Could be using armor?
If you really want scripts only, this is not really reliable but you can try to check if entity got damage if yes chdkx the health how much health he has and dmsage he got, and do calculation and give those missing health back
get what I meant?
Sorta, but looks math heavy
hurt -> get health -> calculate damage and current health -> give back required health
You got no choice, best you could do without using .json, or effects.
I could use armor with protection 4? Would that take less dmg from override?
Ima test it out
Probably? What are you doing in the first place?
... a boss :3
Nono, I meant why you need to reduce the damage?
Is this custom entity? If yes damage sensor already exists.
Ohh, some of the custom weapons use override damage and I don't wanna turn it into a damage checker by raising base hp of the custom entity
I could explain why, but I'd be rambling-
"Triggers item type"?
thanks
They don't stay on memory so that is fine, although, i suggest dynamic properties instead
export function getArea(player) {
const fromArea = player.getDynamicProperty("fromArea");
const toArea = player.getDynamicProperty("toArea");
if (fromArea && toArea) {
const { x: fx, y: fy, z: fz } = fromArea;
const { x: tx, y: ty, z: tz } = toArea;
return { fx, fy, fz, tx, ty, tz };
} else {
return null;
}
}
// Cannot convert to object error
const { fx, fy, fz, tx, ty, tz } = getArea(player)```
Can someone help me
Why does it return "cannot convert to object" error
It'll happen if the object returns null
Check if it really set the values,
Or just ```js
export function getArea(player) {
const fromArea = player.getDynamicProperty("fromArea") || { x: 0, y: 0, z: 0 };
const toArea = player.getDynamicProperty("toArea") || { x: 0, y: 0, z: 0 };
const { x: fx, y: fy, z: fz } = fromArea;
const { x: tx, y: ty, z: tz } = toArea;
return { fx, fy, fz, tx, ty, tz };
}```
And check if the dynamic property is actually a vector3
getBlocks()?
getBlocks already has built-in for that. Dimension.getBlocks(volume, {}, true)
It's Boolean, suppress the unloaded chunk error
hmmm nah bro like i cant fix it
mayb its not a area problem
i think i did smth werid somehwherer
how did u guys got soo good at scriptapi?
it goes like Y infinite
you know what, i also think the same, about the scripting legends
And no if your talking about me, i am not good at scripting
Read javascript.
did u guys read the scriptapi docs?
anyways, custom commands is fun wadahell...```js
system.beforeEvents.startup.subscribe(({ customCommandRegistry }) => {
customCommandRegistry.registerEnum('coddy:grant', ['grant', 'revoke']);
customCommandRegistry.registerEnum('coddy:scope', ['only', 'from', 'through', 'until']);
customCommandRegistry.registerCommand({
name: 'coddy:advancement',
description: 'Grants or revokes advancements',
permissionLevel: CommandPermissionLevel.Any,
mandatoryParameters: [
{
type: CustomCommandParamType.Enum,
name: 'coddy:grant'
},
{
type: CustomCommandParamType.PlayerSelector,
name: 'targets'
},
{
type: CustomCommandParamType.Enum,
name: 'coddy:scope'
},
{
type: CustomCommandParamType.String,
name: 'advancement'
}
],
optionalParameters: [
{
type: CustomCommandParamType.String,
name: 'criterion'
}
]
}, ({ sourceEntity }, ...params) => {
const [action, targets, scope, advancement, criterion] = params;
sourceEntity.sendMessage(`${sourceType} ${JSON.stringify(params)}`);
});
});```
Ofcourese
yeah, why wouldn't? Minecraft bedrock Script APi is a different thing
Im not usign get blocks im using fill and setblock command
ohh
I just use the docs to seach events
And, its not my script, i am updating a very old script to 2.0.0-beta (having pain)
And so he uses commands instead of blockVolume or fillBlocks
And why?
^
i will have pain if i change everything to native fill
hmm
uh
WHY DOES playerInterWithBLock not work for me?
itemUse only work for me
dont work with uninteractable blocks
restart mc or check script version.
use beforeEvents.
your a legend
Now how do i get the first block
it spams lol
ok i rememered isFirstEvent
but it still returs two times
how do I define the inventory cuz const inv = target.getComponent('minecraft:inventory').container; is not working
preview only.
if (!isFirstEvent) return
That's correct
const { container } = player.getComponent('inventory');
for (const slot = 0; slot < container.size; slot++) {
const itemStack = container.getItem(slot);
// ...
}```
it returns two times
okay
i did but still the event fires two times
Try doing console if it returns twice means it's broken if it don't then it's your script

see? Lol... It stupid why that would happen
The find(), firstEmptySlot(), firstItem(), contains() and reverseFind() in inventory component are very freaking useful.
inv ist sill not working:
if (!inv) return target.sendMessage("§cInventory not found.");
for (let i = 0; i < 36; i++) {
const item = inv.getItem(i);
if (!item) continue;
ui.button(i, `§l§f${item.typeId}`, [`§7Amount: §e${item.amount}`], item.typeId, item.amount);
}```
getComponent is not defined
Then your entity doesn't have inventory component.
oh wait let me define player
or you're getting invalid entity.
cuz on my auctionhouse its working
if (!inv) return player.sendMessage("§cInventory not found.");
const ui = new ChestFormData('large').title("§l§eSelect an Item to Sell");
for (let i = 0; i < 36; i++) {
const item = inv.getItem(i);
if (!item) continue;
ui.button(i, `§l§f${item.typeId}`, [`§7Amount: §e${item.amount}`], item.typeId, item.amount);
}
In that that shows entity is not grabbed or defined properly.
function mainMenu(player) {
const form = new ActionFormData()
.title(`Main Menu`)
.button(`§l§5settings`)
.button(`§l§cUndo`)
.button(`§l§qRedo`)
.button(`§l§1Fill`)
.button(`§l§1Paste`)
.button(`§l§1Create`)
.button(`§l§1Circle`)
.button(`§l§1Sphere`)
form.show(player).then(result=>{
const forms = [
command.settings,
command.undo,
command.redo,
command.fill,
command.paste,
command.create,
command.circle,
command.sphere
];
// why does that line return error
forms[result.selection](player);
})
}
what error? The dog eat the cat??
Say the error.
bruh "not a function"
wow chaining operator saves my life
i should realy do practice of using chaning operator
// open menu
world.afterEvents.itemUse.subscribe(e=>{
const {source: player, itemStack} = e
if (itemStack.typeId == "minecraft:wooden_axe") {
let distance = 10
if (player.getBlockFromViewDirection()) {
let {x,y,z} = player.getBlockFromViewDirection().faceLocation
x += player.getBlockFromViewDirection().block.location.x
y += player.getBlockFromViewDirection().block.location.y
z += player.getBlockFromViewDirection().block.location.z
const pLoc = player.getHeadLocation()
distance = Math.sqrt(
Math.pow(x - 0.5 - pLoc.x, 2) +
Math.pow(y - 0.5 - pLoc.y, 2) +
Math.pow(z - 0.5 - pLoc.z, 2)
);
}
if (distance > 6) {
mainMenu(player)
}
}
})````
Theissue with it is the form opening, some wrong calculations in distance or head location maybe,
because the not a function error, only happens when the player is lill far away, and looking on air, btu still form don't open, then it returns the not a function error
import { world } from "@minecraft/server";
const command = {
settings: (player) => player.sendMessage("Opened Settings"),
undo: (player) => player.sendMessage("Undid last action")
};
function mainMenu(player) {
const commands = {
'Settings': command.settings,
'Undo': command.undo
};
const form = new ActionFormData().title(`Main Menu`);
Object.keys(commands).forEach(text => form.button(text));
form.show(player).then(result => {
if (result.selection === undefined) return;
const commandNames = Object.keys(commands);
if (result.selection >= 0 && result.selection < commandNames.length) commands[commandNames[result.selection]](player);
});
}
I literally created it.
Like wtf.
huh
I recreated it.
okay
Wtf is this redundancy?
wddym redundancy
You're calling multiple getBlockFromViewDirection
hehe
ik ok ill fix
And what are you doing?
staring at you
I mean,
trying update a Old WorldEdit script to 2.0.0-beta
guysss I get error on line 11 but on line 11 is nothing
error and code
itemUseOn is not in 2.0.0-beta
Checking if the block is 6 blocks ways from
did you do /reload
Dude playerinteractwithBlock still fuckin exist
playerIneractWithBlock
AIR
yes
full code
You didn't say that in the first place...
Checking if there's 6 blcoks of air from view direction of player?
playerInteractBlock is to detect interacting with block , i am detecting when the item is used in air, player cant interact with air. itemUse is the only way
can't show u the full code cuz its too long
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
import { showJobsMenu } from "./plugins/jobs.js"
import { openEditor } from "./plugins/chestui.js"
import "./essentials/chat_commands.js"
import "./plugins/invsee.js"
import "./plugins/auction_house.js"
let uiStorage = {};
const bannedPlayers = new Set();
let worldSettings = {
welcomeMessage: "§6Welcome to the server!",
canBreak: false,
canPlace: false
};
const kits = {};
function saveAllUIs() {
try {
world.setDynamicProperty("gravel_ui_storage", JSON.stringify(uiStorage));
} catch (e) {
console.warn("§c[ERROR] Failed to save UI storage:", e);
}
}
function loadAllUIs() {
try {
const raw = world.getDynamicProperty("gravel_ui_storage");
if (raw) {
uiStorage = JSON.parse(raw);
}
} catch (e) {
console.warn("§c[ERROR] Failed to load UI storage:", e);
uiStorage = {};
}
}
system.runInterval(() => {
for (const player of world.getPlayers()) {
const tag = player.getTags().find(t => t.startsWith("open:"));
if (!tag) continue;
const name = tag.split(":")[1];
const ui = uiStorage[name];
if (ui) {
showGeneratedUI(player, ui);
} else {
player.sendMessage(`§cUI "${name}" not found.`);
}
player.removeTag(tag);
}
}, 20);
just a part
:
Answer me.
very sus why would it return error on a empty line
yes
its spamming my chat
I think im just disturbing you guys, the "not a function" is a lil rare errror. if it works it works lmao hehe
Spamming in chat?
I think you meant console
And? I don't complain or something
If I help, I will help lol
If you want answer, Yes
I deleted the code and its still line 11 😭
Then its runningn another script, else manifest is wrong, else you didnnt import it
So its not a code fault
the logs 😭
you are using development_behavior_packs?
no
you should
but after reload the script is changing
no
no?
I meant, no, the sccript is not reloading, if your not using devellopment folder
ohhh
the game take a copy of behavior packs if they are on behavior_packs, so changing the ones in behavior_packs change nothing
oh ok
i accidentaly reacted a sklull to your messege "you should" you might've thought that i am not telling him to use development pack folder lol
np
world.beforeEvents.itemUse.subscribe(({ source, itemStack }) => {
if (source.typeId !== 'minecraft:player') return;
const head = source.getHeadLocation();
const view = source.getViewDirection();
if (itemStack.typeId === 'minecraft:wooden_axe') {
const blockRay = source.dimension.getBlockFromRay({ x: location.x, y: location.y + 0.1, z: location.z }, view, { maxDistance: 10 });
if (!blockRay.length) return;
const { block, faceLocation, face } = blockRay;
const distance = Math.sqrt((faceLocation.x - head.x) ** 2 + (faceLocation.y - (head.y + 0.1)) ** 2 + (faceLocation.z - head.z) ** 2);
if (distance > 6) {
// ...
}
}
});```
or ```js
world.beforeEvents.itemUse.subscribe(({ source, itemStack }) => {
if (source.typeId !== 'minecraft:player') return;
const head = source.getHeadLocation();
const view = source.getViewDirection();
if (itemStack.typeId === 'minecraft:wooden_axe') {
const blockRay = source.dimension.getBlockFromRay({ x: location.x, y: location.y + 0.1, z: location.z }, view, { maxDistance: 6 });
if (blockRay.length) return;
const { block, faceLocation, face } = blockRay;
// ...
}
});```
ayo thanks!
what do i replace location with
for?
do you know how to access the equipment worn on an armor stand?
can't
what for?
its not rlly nothing specific i was just coding a circle made out of armor stands and i was seeing if you could put a helmet on all of them through the code
use commands
how would i do that?
entity.runCommand("replaceitem entity @s....")
yeah ty
but isnt that basically just doing what get component would do?
equipment don't work on none player entities
right didnt know that sorry thanks for help
that's a bit silly that equippable doesn't work on non-players. hopefully this gets updated at some point
does anyone actually play preview? i made a simple homes addon using the new command registry (mainly for when it goes stable) but i don't know if anyone would actually use this at the moment.
preview is used mainly in testing
fair enough
Installation for @minecraft/server
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
Installation for @minecraft/server
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
Installation for @minecraft/server-ui
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
How does this work?
https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/datadrivenentitytriggerafterevent?view=minecraft-bedrock-stable
It just reads the entity events
Yeah essentially.
The output can be used to run other events using more script like getModifier?
Yeah.
Example please? Brain not braining:(
You can do whatever the heck you want with the output inside scripts
So essentially, if I use sensors inside a mob that runs events, either for movesets or mode_changer, the script could read that and run other things alongside it?
Absolutely
Like, if for example the entity sensor detects a target entity far enough away, it could run an event that makes it angry, adding the component group, which then activates like.. applyImpulse to "dash" towards the target?
There could be more efficient ways to do this.. but maybe using timers on single component groups that cycles through?
Totally possible
You could even have the entity sensor inside of scripts, using a getEntities on a consistent loop to detect close by mobs
You will have to learn javascript, just be warned 😛
I can wing it, people say I'm pretty fast at learning :3
-# only one person has said it
So long as the sacred texts can provide me a template, I'll try
If you're willing to learn you're halfway there 
I guess the next simplest step forward is adding a script that applies a dash mechanic for when target entities are too far away. I'd assume that I can run a function that gives the entity resistance for immunity
The deep always know where to seek, as they say.
such as cancelling entity damage

when will mojang ever add entituHurt beforeEvent
Do you need it? I have made one for components
You can mimic it with damage sensors, but having the ability inside scripts is very valuable
(Such as reading the amount of damage dealt and modifying it)
i know right canceling damage is possible with damage_sensor component
Mathematics :(
guys, how can i make my addon runs the scripts?
There is a.. component? For that, right?
you mean JSON ?
you have to put your main.js path to your manifest.json.
Yesh
how to check if player started breaking block? Is it possible with
itemUseOn or entityHitBlock event
ah, how do i implement it? i mean the object to add the path
Most of my addons just have a lot of json file for detecting on hit and running random functions, or just a function, and another for just removing duplicate mobs
You must have to hit the block first, to start breaking right?
so the perfect event for you would be entityHitBlock.
Then yeah, damage_sensor component
One more thing, applyImpulse for entities, and applyKnockback for players?
Yes.
applyImpulse() doesn't work for players.
Hmm. I might just use applyKnockback for all then?
but applyKnockback() also works for entities
but not dropped items ("minecraft:item") you got to use applyImmpulse to push them
there are also some cases where applyKnockback not work for entitites
the items are fin-?
Is it rare to occur?
is this good implemented?
Yes
I guess I'll just have to take my chances with 3 tp commands in a function
i think so
there is native method for teleporting
entity.teleport({})
i made a little command that say hello world, but doesn't execute
Do you want to execute the "hello wold" messege once upon joining the world? or execute it eveery tick
execute once time
Also, make sure your script version is 1.18.0 (latest stable) or 2.0.0-beta (latest beta) in manifest.json
if your using bridge v2, it sets @minecraft/server to 1.0.0-beta once upon creating a project, idk why
So you'd have to set it manually if you haven't
i see
You should use 1.18.0
world.afterEvents.worldInitialize.subscribe(() => {
world.sendMessage("Hello World!")
})
i see
only for 1.18.0
worldLoad if using 2.0.0-beata
you dont have to care about that
thats the pack version right
or mayb a dependency version
yes but wrap it with try catch because it can throw for specific entities
Template for what
For the dash, I mean
wdym sleeping on it
Sleeping on it to like, sleep to get a fresh mind for it.
Dash as in using applyKnockback to "dash" either from being called thru events or on use of an item/weapon
I have a player input someone let me kindly use so I can experiment with it
Yh but it says I breaked air when I break block in creative
world.afterEvents.entityHitBlock.subscribe(({ damagingEntity: player, hitBlock: block }) => {
if (!player || !block) return;
const id = block.typeId;
console.warn(id);
});
If your in creative, you can't detect if player sarted breaking block
bcoz creative instantly breaks the block....
so there’s no way to detect it in creative?
world.afterEvents.itemUse.subscribe((event) => {
const { itemStack, source: player } = event;
if (itemStack?.typeId === "your_dash_item" && player instanceof Player) {
player.applyKnockback({x: 0, y: 0}, 1) //example
}
})
I still didnt understand what you meant by sleeping on it/ fresh mind
Ofcourse no
Oh you just want the block
then use playerBreakBlock event
Waw thanks! :0
in entityHitBlock you'd detect if player is in survival
and in playerBreakBlock event, you;d detect if player is in creative
@coral ermine
Bcoz firing the event when starting to break the block could be only possibgle in survival
and using entityHitBlock makes no sense in creative, since creative instantly breaks block.
a little doubt
hmm, how do i refresh the files after i modified and saved the changes?
/reload
on bedrock, right?
uh, yeah?
The server is about Bedrock
else if (message == ".suicide") {
data.cancel = true
return player.runCommand(`kill @s`);
}
Ok 👍
do you know what could be wrong?
else if (message == ".suicide") {
data.cancel = true
system.run(() => {
player.runCommand(`kill @s`);
})
}
use the fixed code i sent you
would that lag the game?
No
Player.kill()
☝️ Yeah, there is native method for kiling
does system,runJob help in multithreading ?
Yes
Yes
system.runJob
Queues a generator to run until completion. The generator will be given a time slice each tick, and will be run until it yields or completes.
Bro changed his answer to Yes
THATS VERY WILD
I have a loop that lags when there are more than 20 players
Script api isn't multi threaded
😂 i take my loses if im wrong
if I use system.run Job for my loop , will it actually help?
depends on what you do
system.runJob queues each work until completion, so it doesnt just instantly run that, and by making a stop/queue, it can somehow help in multithread like suppose you want to do antoher task at the same time
Any tips when it should be used?
And multithread is used here a pseudo word, like it means here to not make the game overloaded with the task, but not like the CPU multitaksing
filling/breaking large area of blocks at once
the process is run in slices before other sync stuff are run i think
well that's what i understand from this picture https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.System-2.html
I have a gun firing system
detects itemuseage and starts a runinterval to shoot out the projectiles
I use a loop that runs non stop for the player to show ammo count and some parameters using actionbar.
I meant, system.runJob divide one task, you can see in the picture, it runs at first, "until" the "task" is complete. then it runs system.run, and if you can even somhow divide the task, and you wrap the task in system.run, it will run each tick, which will make the task run so slowly, runJob is to not make the game overload, and but to keep the task efficient at the same time.
It's just your preference, you might have not to use runJob here
so there are no other ways to optimize the runinterval?
idk
random question but does anyone know how to scale gui below -1
Exit the execution early if certain conditions fail.
Only update when the amo count changes. Otherwise, use a higher interval when renewing the actionbar to reduce the TPS load.
what? no
script api run single threaded, and all scripts share the main game thread
runJob only help with offloading heavy calculations by scheduling "jobs" to be run asynchronously to prevent blocking other scripts
Since you're showing something and not a heavy operation you should stick with system.runInterval()
There's a chance where system.runJob() would instead run .setActionBar() more than once in the same tick, which is redundant
umm
how do I do a scrolling effect with herobrines chestui?
or actionformdata
idk
would anyone be able to help me with actionformdata in vc im poo at js
function ui(player) {
const test = new ActionFormData()
.title("test")
.button("test")
.show(player).then(res => {
if (res.canceled) return;
if (res.selection == 0) {
player.runCommand("say test")
}
}
}
should work
Not what i meant
if you want I can help you rn, I won't talk tho
Okay ill join in 1 second
how do I add the player health?
const health = Entity.getComponent('health');
const current = health.currentValue; // imagine it's 5
health.setCurrentValue(health + 10); // output: 15```
Edit settings 🤷
its not working I don't see more healths on my health bar:
const { damageSource, deadEntity } = event;
const killer = damageSource?.damagingEntity;
if (!killer || !killer.hasTag("lifesteal:on")) return;
if (!killer.hasComponent("minecraft:health")) return;
const health = killer.getComponent("minecraft:health");
const currentMax = health.currentValue;
if (currentMax < MAX_HEARTS) {
health.setCurrentValue(currentMax + 2);
try {
killer.runCommand(`titleraw @s actionbar {"rawtext":[{"text":"§a+1 Heart (Lifesteal)"}]}`);
} catch (e) {
console.warn("runCommand error:", e);
}
}
});
more hearts*
Because that's not possible
You can't make show more heart bars without using health boost.
ohhh
It set current value but not max value.
but health_boost gives u 2 hearts per amplifier
Good evening, can someone help me with JS? I need to launch an entity in circles around another one to simulate a tornado. But I can't think of any function that would help me do that.
Sorry for the English, I'm Brazilian and I asked ChatGPT to translate this for me.
Would my script run without error with this logic, WITHOUT anything in the pack to add the player beforehand? js if (world.scoreboard.getObjective("deathCount")) if (world.scoreboard.getObjective("deathCount").getParticipants().includes(deadEntity.scoreboardIdentity)) if (deadEntity instanceof Player) world.scoreboard.getObjective("deathCount").addScore(deadEntity.scoreboardIdentity, 1)
I'm making a script for basic statistics, but I would like to have the option of not making the score in the first place or choosing only certain players.
You want to increase death score of player?
^
Yes. I'm going for all the non-compound scoreboard criterion that Java has
Air, food, health, levels, xp, and armor
I mean, without initializing scores you can just addScore() it immediately.
And all the kill/deaths ones
^
Don't be mad lol
I just answered this because you literally answered "yes"
I'm just asking if it would work (as in, not work but continue the code without error) if there was either no score or no player on that score, or both
as I said, you don't need to initialize scores if you're setting a score on player in a specific objective, you just do that if it's getScore(), it returns undefined if player don't have score in the objective... And you know that...
no fancy BLA BLA, just directly add score.
That's why it has if (world.scoreboard.getObjective("deathCount").getParticipants().includes(deadEntity.scoreboardIdentity)) 💀
if ((obj?.getScore(player) || 0)) {}```
Happy? Also can't you just check it?
Not in singleplayer ._.
and?
Oh wait
It counts all deaths
Nevermind
Still no though
I like to have my scripts "finished" before testing
And so far, I can't figure out how to the get the current armor or food values of the player
How do I do that?
okay? Then good luck finding error root by root if you go test it thinking it actually works.
I don't understand properties or dynamic properties so unless you tell me that one of the properties of the player carries it I can't use them
vanilla armor yes, custom no, for food values someone did in the #1067535712372654091 I you meant the hunger bar the food game....
you don't read docs?
The hunger bar
Not really
You can't.
Dang
read then.
And I assume the one in the script resources is an extremely convoluted script that checks for what armor the player is wearing, which I have to run every couple of ticks for refresh and will cause a lot of lag
I guess I'm not making armor or food stats
const dp = Entity/Player/ItemStack/World.getDynamicProperty('<name>');
Entity/Player/ItemStack/World.setDynamicProperty('<name>', <value | Boolean | String | Number | Vector3 | undefined>);```
This are very straightforward they're not that hard to understand
you can store DP in world, player, entity, and item.
It's more "WHAT PROPERTIES ARE THERE ALREADY" and "HOW CAN I ACTUALLY SET MY OWN"
ignore what is aid there since what I meant in script resource is the food values...
read docs my guy??
The docs are so damn long and hard to find relevant information for what I'm doing usually
I guess search button doesn't exist?
Barely functional
either your lazy to find or you suck at finding.
Sure
what site are you using in the first place?
Don't tell me Microsoft docs.
learn.microsoft.com and minecraft.wiki and bedrock.dev sometimes
if yes just use stirante or jayly
Never heard of em
they're small in terms of information, use what I suggested for scripts.
ohh no...
Now I'm not surprised why you always asked for properties players/items or blocks has...
Yep
The only shit I know how to do for the most part are things Bridge can autocomplete
just use vscode like....
On iPad?
Bro even on pc I don't know how to properly use or install schemas and what about other behavior/resource pack stuff??
hows this 🙂
yes and format codes
Ahh you used the one you made in #1067535712372654091
yep 😄
You used runJob() for checking?
now make it pixeleprfect... Jk
any good char to use as block ? rn i am using §l#
what is the item component in item json for setting item to be enchanted as a sword eg it can have mending, unbreaking, etc
#1067869136606220288 please.
mb
I guess not? Best I could think of is custom emojis
Then use char code.
Video clearly using RP
for addons*
man I'm really trying my best to use the new container methods we got recently, but they all just seem so... useless
The one I did manage to use, isStackableWith, doesn't seem to have much of a use when you can check typeId == typeId
It probably takes into account Lore, NBT, and dynamicProperty differences, not just typeId.
Example: Tipped arrows share the same typeId as an arrow
that is true
they take into account if the item max stack size tho, so keep that in mind
isStackable is ItemStack and ItemStack....
and iirc if it's unstackable it returns false...
What is that, unicode?
emoji
^
What are you doing here 🤔
is that default ?
yes
oooh now i got it lol
that is unicode
as you can see
but i remembered something
wait
-# I was right
I'm aware, but you can just do typeId == typeId. If it's unstackable it returns false, but you can also just check amount to maxAmount. Additionally, it doesn't return whether that specific itemStack is stackable, only if the item itself can be stacked, so you still have to do additional checks beyond that.
would be better if the contains() method used itemType
That's one of the way to counter item with shared id tho
typeId == typeId. If it's unstackable it returns false
no
so great, now you know the item can be stacked! now you have to do
if(currentInventoryItemAmount + amountToAdd > currentInventoryItemMaxAmount) {
currentInventoryItem.amount = currentInventoryItemMaxAmount;
inventory.setItem(i, currentInventoryItem);
amountToAdd -= (currentInventoryItemMaxAmount - currentInventoryItemAmount);
}```
Which you were already going to have to do
that doesn't behave as I believe it should be
plus, it stacks automatically
addItem does not, it fills into the next empty slot
-# Only stacks if it has the same data obviously
If you want it to go into the available stacks, you have to search the inventory manually first
it check items before that
It does not
addItem returns the remaining ItemStack if it could not add it to the inventory in general
Not the slot
I think Koala means that addItem() will prioritize the first empty slot then an existing item of the same type
^
The best solution is:
- Manually search through inventory for available stacks and add to those
- use addItem
- spawnItem
it does not ....wt😣
that's essentially how /give works
Ah yeah it does that
I hate it
I was pretty much done fixing my function that I have left untouched for months to cover any special cases and thought I was done
but I'm trying to cover if someone tries to add like 2000 of something
Solution: don’t
well, I need to cover it for one of my crafting systems, I haven't exactly checked the theoretical max and whether it would ever be an issue
i noticed that in minecraft movie event
like, why does it keep going into my hotbar?
💀
give @s item 😅
but I might as well make it flexible anyways
didnt koala say thats how give works aswell
the issue with this is that new ItemStack only allows up to an amount of 255
wat
I misunderstood what koala said ig
i am questioning my memory now, that can't be true
@distant tulip
I believe this message had to do with this message though
It did
yeah, I misunderstood.
had to double check in game, lol
lol
now i can sleep peacefully
-# 2 AM
I'm 6 hours in the future
welp time to see if what I did works or if I'm about to crash my game with an infinite while loop
im still wondering if theres a way to prevent crashing from infinite loops
-# especially when i accidentally mess up with nametags
you just don't use while loops
an infinite loop will always crash any game at some point
man i wish watchdog was useful for this
I don't see what watchdog would do
"Your game is about to crash"
0.1 seconds before it crashes
-# zzzz not if it is in a runJob
run a job
lol, give me a sec
thanks
a function under the system class that uses generator function to run a set of tasks in different times
Generator functions have something called yeild, when the runjob run the function and reach a yeild it stops the execution and resume it next time the game is free
oh so it basically gives the game a 'work' to do instead of making them to do it immediately
yeah
thats nice
it is like
normal functions: stop everything you are doing and do this now
runJob + Generator functions: Do this when you can, when ever you have free time work on it a bit
system.runJob()
You give Bob 🐟 a job. Bob is lazy. If it is too much work he'll do it the next day. If it's easy, he does it more on the same day
Your brain need to be paid for staying awake that long
watchdog would put them in sleep
-# auto wake up at 7 😫
how are you all doing today
kaboom
is there a way to get the total of entities killed within a certain attack action?
let killCount = 0;
world.afterEvents.entityDie.subscribe(({ damageSource, deadEntity }) => {
const dmgSource = damageSource.damagingEntity;
const validEntityTypes = Object.keys(entityAbilities)
const victimHealthComp = deadEntity.getComponent('minecraft:health') as EntityHealthComponent;
if (!dmgSource || !validEntityTypes.includes(dmgSource.typeId) || !victimHealthComp) return;
const isTamed = dmgSource.getComponent('is_tamed');
if (!isTamed) return;
addExperience(dmgSource, xpReward(victimHealthComp.effectiveMax) * killCount);
});
Or would I have to use the entityHurtEntity event to increase that value
Does attack action refer to the damage type dealt? Or the way they're killed?
how do i set the lore of an item in scripting?
const item = new ItemStack("apple",1);
item.setLore(["line 1", "line 2"]);
i tried that but off an item use event and it didnt work
You need to actually set it to the player inventory.
const inv = player.getComponent("inventory").container;
inv.addItem(item)
or
inv.setItem(player.selectedSlotIndex, item)
right so i defines the new item data so i set that to the ibnv?
inv?
yes inventory
alr ty
addItem() to add the item to the first empty slot. Automatically stack with a similar item
setItem() to override specific slot
yeah ty again
You don't really need to define a new one. If the event gave you the itemStack property, I suggest to use it instead.
It'll retain its old data like its name, Lore, enchantment, etc.
ItemStack is like a "snapshot" of the item at the time it's gotten (event fire, getItem, etc) and is not related to the inventory in any way.
how do i get auto sugestions like if i do world. then it will show me what i can do im using vscode
I just search on YouTube blindly. Took me an hour.
??
like "npm i @minecraft/server@latest"?
"Bedrock Scripting set ups guide"
where is this
Search it on youtube
alr ty
Might not get what you want. You need to improvise and search more or use different wording
Damage type, I'm applying damage with the tamed entity being the cause of damage. Every victim that is killed should be accounted for. Exp reward should multiply if the damage kills more than 1 entity. That's why I have the killCount set
Use dynamicProperty. That killCount variable will be shared with other player pets and won't be saved between world loads
Like this:
const killCount = (dmgSource.getDynamicProperty("killCount") ?? 0) + 1;
dmgSource.setDynamicProperty("killCount", killCount);
xpReward(victimHealthComp.effectiveMax * killCount);
can itemStartUse and itemStopUse desync?
trying to make right click hold detection but im worried if anything can go wrong
It's unlikely.
hopefully
cant believe i have to do ALL OF THOSE to check for shield block check
man only if i could use is_blocking query in scripting
Ohh no gega become anime girl...
Oh no, It's a disaster indeed
Is there something like this I could use but attachables giving effects instead?
import { world, system } from "@minecraft/server";
const helmetParticle = {
"minecraft:diamond_helmet": "...",
"minecraft:golden_helmet": "...",
//...
};
system.runInterval(() => {
for (const player of world.getPlayers()) {
const equipment = player.getComponent("minecraft:equippable");
if (!equipment) continue;
const helmet = equipment.getEquipment("Head");
if (!helmet) continue;
const particleId = helmetParticle[helmet.typeId];
if (!particleId) continue;
const playerPos = player.location;
const spawnPos = {
x: playerPos.x,
y: playerPos.y + 2, // spawning above the head
z: playerPos.z
};
player.dimension.spawnParticle(particleId, spawnPos);
}
}, 10); // 0.5 seconds
you can link animation on attachable, then spawn particles from the anination
Im already using this script for particles. I'm wondering if I can use a similar script for adding effects(like Invisibility) also?
Also I switched to script because doing it that way wasn't working with the locators.
You can do the particle thing with only a resource pack. But applying potion effects like invisibility needs to done on the server
What?
player.addEffect("haste", duration, {
amplifier: 100,
showParticles: false
})
-# missread your message there
Sorry. Where would that go?
I'm trying to add effects to multiple attachables like above is spawning particles for multiple attachables.
Nevermind. I think I figured it out
Not edited, just new one that doesn't spawn the particle
const helmetEffect = {
"minecraft:diamond_helmet": ["haste",{ amplifier: 2 }],
"minecraft:golden_helmet": ["invisibility",{}],
//...
};
system.runInterval(() => {
for (const player of world.getPlayers()) {
const equipment = player.getComponent("minecraft:equippable");
if (!equipment) continue;
const helmet = equipment.getEquipment("Head");
if (!helmet) continue;
const effectData = helmetEffect[helmet.typeId];
if (!effectData) continue;
player.addEffect(effectData[0],10,effectData[1])
}
}, 10); // 0.5 seconds
system.runInteral(() => {
for (const player of world.getPlayers()) {
const equippable = player.getComponent('equippable');
const head = equippable.getEquipment('Head');
const location = player.location;
if (head?.typeId === 'minecraft:netherite_helmet') {
player.dimension.spawnParticle('', { x: location.x, y: location.y + 2, z: location.z });
player.addEffect();
}
}
});```
Aww man :(
Oh thank you!
If I needed it to do chest instead would I just change all the "helmet" to "chest"?
And head to chest
yes, but it's case sensitive iirc
Thank you!
It's working!
Is there a way for me to make it where the effect particle doesn't show?
Is that the last "1"?
const armor = {
'minecraft:netherite_helmet': {
particle: 'minecraft:redstone_wire_dust_particle',
effects: [
{ 'minecraft:speed': { amplifier: 0, showParticles: false, duration: 100 } },
{ 'minecraft:blindness': { amplifier: 255, showParticles: true, duration: 100 } }
]
}
};
system.runInterval(() => {
for (const player of world.getPlayers()) {
const equippable = player.getComponent('equippable');
const location = player.location;
for (const slot of ['Head', 'Chest', 'Legs', 'Feet']) {
const equipped = equippable.getEquipment(slot);
const config = equipped && armor[equipped?.typeId];
if (config) {
for (const effectObj of config.effects) for (const [effectId, options] of Object.entries(effectObj)) {
const { duration = 20, ...rest } = options;
player.addEffect(effectId, duration, rest);
}
player.dimension.spawnParticle(config.particle, { x: location.x, y: location.y + 2, z: location.z });
}
}
}
});```
I am weird. Wtf.
Oh that does everything? For any armor slot?
Just watching it change trying to learn 🤣 👀
Yahh.
Just check how I add IDs with effects duration, amplifier, visibility and particle name.
const helmetEffect = {
"minecraft:diamond_helmet": ["haste",{ amplifier: 2 }],
"minecraft:golden_helmet": ["invisibility",{ showParticles: false }],
//...
};
oh ok! thank you !
the multithread is used here a pseudo word, like it means here to not make the game overloaded with the task, but not like the CPU multithreading
Coddy (dyodC) have it more advanced and compact tho
Oh hey you got a nice pfp!
weren't you a TNT before-
Yesn't
That's very old one...
I was redstone block before.
Yeah lol
I will use that one later most likely when I have things more fleshed out. but I'm just testing things for now with chests and effects.
Perhaps I need to ask here, as help that I've gotten else where has not worked.
I am having issues with custom armor stand made through block bench.
They refuse to place facing forward. And when adding the axis aligned component all it does is shake, same happens if I add the blocked component.
Is it possible to script that it can only be placed in 8 directions or that it auto aligns when placed? This has been drying me insane for the past 2 weeks.
The one that is not shaking is how it is without axis aligned or blocked. Other is with
That is just a default armor stand appearance, armor stand behavior entity created through block bench
I was told it shakes because of the runtime_identifier but removing that makes it not act like an armor stand anymore
how is the entity face in that direction?
probably need to see the json
#1067869022273667152
It has been cycling through 100k and 99999 for the past months
I posted there the other day. Just added the json to the post
I did. It was the json but it was forwarded from chat. So I deleted it cause I downloaded the file and put it in entities as that says
Sorry. I tagged saying that was the only way I could show the json currently being on mobile and didn't have access to the file
Am i a dumbie head
this new movement correction is so annoying
If you run, jump and hit someone, you get moved backwards
for every action there is an equal and opposite reaction 
lol
huh
I made the namespace / lol
that looks illegal
Don't worry it doesn't work, I already expected it since // is already invalid.
try §: lol
the namespace is annoying shucks
Ok wait....
can you use \0 as a namespace
The preview is broki, if you're in textbox, it shows 7 otherwise it would show f
Yah.
preview?
hmm.
wait, I'll try yours and Minato.
you typed just §: ?
it is
yah just typing /§ does that lol
thanks
huh, weird
I think the namespace you really can't use is the classic Minecraft and /
Using / namespace still registers the command since it exists tho you can't use it since in general // is invalid.
how do I cancel event from a entity like villager
What kind? trading with them?
Try commenting out the runCommand and add a console.log.
Do you have valid dynamic property saved on that entity
ok
because you also checking if the entity has the dynamic property, so you have to make sure if the entity has the dynamic property
okay
Thanks I'll give it a try
Just do console.warn() on after each line, and see which line doesn't execute
Then you'll know what line has the problem
oooo
I usually go with mostly red and yellow for highlights for warning message
I thought a combat tag was a warning since most punished you after relogging
it is a notification
the highlight of the message is the name so it should be with a color that stand out better then the info itself
world.afterEvents.entityHitEntity.subscribe(({ hitEntity, damagingEntity }) => {
if (!damagingEntity?.hasTag("ws:combat") && (damagingEntity?.typeId === "minecraft:player" && hitEntity?.typeId === "minecraft:player")) {
damagingEntity.addTag("ws:combat");
damagingEntity.sendMessage(`§eYou are in combat with§r §6${hitEntity.name}!`);
hitEntity.addTag("ws:combat");
hitEntity.sendMessage(`§eYou are in combat with§r §6${damagingEntity.name}!`);
system.waitTicks(6000).then(() => {
damagingEntity.removeTag("ws:combat");
hitEntity.removeTag("ws:combat");
hitEntity.sendMessage(`§eYou are not anymore in combat!§r`);
damagingEntity.sendMessage(`§eYou are not anymore in combat!§r`);
})
}
})
is this code right
I dont have minecraft to test :p im srorry
world.afterEvents.entityHitEntity.subscribe(({ hitEntity, damagingEntity }) => {
if (!damagingEntity?.hasTag("ws:combat") && (damagingEntity instanceof Player && hitEntity instanceof Player)) {
damagingEntity.addTag("ws:combat");
damagingEntity.sendMessage(`§eYou are in combat with§r §6${hitEntity.name}!`);
hitEntity.addTag("ws:combat");
hitEntity.sendMessage(`§eYou are in combat with§r §6${damagingEntity.name}!`);
system.waitTicks(6000).then(() => {
damagingEntity.removeTag("ws:combat");
hitEntity.removeTag("ws:combat");
hitEntity.sendMessage(`§eYou are not anymore in combat!§r`);
damagingEntity.sendMessage(`§eYou are not anymore in combat!§r`);
})
}
})
u mean this
?
what error not have priviliges?
No errors in [code](#1067535608660107284 message)
can somone tell what this error mean
Something on line 55 only wants string. But you feed it something else
ohh
oh yea runCommand
const player = event.player;
const entity = event.target;
console.warn("test")
if (!player || !entity) return;
console.warn("test1")
const command = entity.getDynamicProperty("command");
console.warn("test2")
event.cancel = true;
console.warn("test3")
system.run(() => {
player.runCommand(`${command}`).then(() => {
player.sendMessage(`§a✔ Command executed: §r${command}`);
}).catch(() => {
player.sendMessage(`§c✖ Failed to run command: §r${command}`);
});
})
});
what is wrong here
command is undefined but why
command is empty, or basically undefined. You didn't set the dynamicProperty
const entity = player.dimension.spawnEntity(type, player.location);
entity.nameTag = nameTag;
entity.setDynamicProperty("command", command);
player.sendMessage(`§a✔ Spawned ${type} with command: §r${command}`);
} else {
player.sendMessage(`§ePreview only. No entity spawned.`);
}```
btw I get the message
Just do if (!command) return; and it'll hide the error 💀 but not fix the problem
What’s line 61
runCommand
from the error commandSyntaxError I guess its the runCommand
player.runCommand(`${command}`).then(() => {
Btw that .then() is unnecessary.
Yeah
no to know if the command was found
Run command does not return a promise
sometimes the command not found idk why
then() is for Promises. That's is usually what runCommandAync returns after execution. runCommand doesn't
It doesn’t directly translate


