#Script API General
1 messages · Page 13 of 1
It...literally does
Adding it shows this
did u do the scripting part?
Use 1.20.80
hmm, its in preview
so not in the stable ver
It is
the blocks work
Jsut beta apis
is it on 12-beta or 13-beta?
did you managed to find what causes the problem?
you can't at the moment, but i think you can just edit lang files for script event command feedback
oki
function Quest(player) {
const chestui = new ChestFormData('9')
.title('§l§d Quests')
.pattern([
'xxExOxYxx'
], {
x: { itemName: '', itemDesc: [], enchanted: false, stackAmount: 1, texture: 'minecraft:magenta_stained_glass' },
a: { itemName: 'Anvil', itemDesc: [], enchanted: true, stackAmount: 16, texture: 'minecraft:anvil'},
O: { itemName: '§l§4Kill quests', itemDesc: [], enchanted: true, stackAmount: 0, texture: 'textures/items/netherite_sword'},
E: { itemName: '§l§bTime quests', itemDesc: [], enchanted: true, stackAmount: 0, texture: 'textures/items/clock_item'},
Y: { itemName: '§l§jMining quests', itemDesc: [], enchanted: true, stackAmount: 0, texture: 'textures/items/iron_pickaxe'},
})
.show(player).then(response => {
if (response.canceled) return;
switch(response.selection) {
}
})
}
does anyone know how to get the selection from patterns?
It's in the components part. And that's a bug I get that too cuz hfc is still in it
Hfc still being there itl be taken our soon
You can turn off HCF on a world using a third-party editor
Well you should ask the owner of that lib
ChestFormData is not native form
Selection for pattern works the same as regular form
Latest NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Beta APIs NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Preview Latest NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Preview Beta APIs NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
async function giveArmour(player) {
const equipmentCompPlayer = player.getComponent(EntityComponentTypes.Equippable);
const boots = equipmentCompPlayer.getEquipment(EquipmentSlot.Feet);
const leggings = equipmentCompPlayer.getEquipment(EquipmentSlot.Legs);
const chestplate = equipmentCompPlayer.getEquipment(EquipmentSlot.Chest);
const helmet = equipmentCompPlayer.getEquipment(EquipmentSlot.Head);
const dimension = player.dimension;
const entity = dimension.getEntities({
closest: 1
});
const equipmentCompPlayer2 = entity.getComponent(EntityComponentTypes.Equippable);
equipmentCompPlayer2.setEquipment(EquipmentSlot.Feet, boots);
equipmentCompPlayer2.setEquipment(EquipmentSlot.Legs, leggings);
equipmentCompPlayer2.setEquipment(EquipmentSlot.Chest, chestplate);
equipmentCompPlayer2.setEquipment(EquipmentSlot.Head, helmet);
}
I've got this error and not sure why
Entity cannot get equipment component
how would I go about giving the nearest entity to a player the armour that the player is wearing?
only way atm is using something like replaceitem 
I tried doing that before but when getting the component for the armour on the player, the reference is an object which cant be used in the replaceitem command
Can you show what you did?
I don't have the exact code but if I remember correctly I didnt have any of the equipmentComp2 stuff and then just tried replaceitem command and using the variable helmet etc.
ah, you'd need to replace on the item's typeId property- getEquipment() returns an ItemStack, which, when converted to a string (like most objects) it will show up as [object Object].
The typeId property returns a string which is the item ID, and can be used in the replaceitem command
May I see an example?
entity.runCommandAsync(`replaceitem entity @s slot.armor.feet 0 ${boots.typeId}`);
ohh I see what you mean now, I'll give that a try and let you know how it goes
tyty
async function giveArmour(player) {
const equipmentCompPlayer = player.getComponent(EntityComponentTypes.Equippable);
const boots = equipmentCompPlayer.getEquipment(EquipmentSlot.Feet);
const leggings = equipmentCompPlayer.getEquipment(EquipmentSlot.Legs);
const chestplate = equipmentCompPlayer.getEquipment(EquipmentSlot.Chest);
const helmet = equipmentCompPlayer.getEquipment(EquipmentSlot.Head);
const dimension = player.dimension;
const entity = dimension.getEntities({
closest: 1
});
entity.runCommandAsync(`replaceitem entity @s slot.armor.feet 0 ${boots.typeId}`);
entity.runCommandAsync(`replaceitem entity @s slot.armor.legs 0 ${leggings.typeId}`);
entity.runCommandAsync(`replaceitem entity @s slot.armor.chest 0 ${chestplate.typeId}`);
entity.runCommandAsync(`replaceitem entity @s slot.armor.head 0 ${helmet.typeId}`);
}
I'm still getting the same error
oh- getEntities also returns an array (even though you are using the closest property)
you can define entity as the first returned element by doing const [entity] = ...
using the closest property does also require a location to run off of
yup that was a stupid error on my side there, should've saw that
location: player.location?
If that's what you want, sure
Do note that the closest may be the player themselves, in that case
I'll just add a family exclusion if thats the case 👍
got it working now thank you for the help!
excellent!
Hfc is still in the game it still throws errors for it even if it's not activated
If you version your block & items they should not throw errors
I do not use HCF, and none of my custom stuff throws errors
Yeah that's ehat I was getting. I fixed my items
How should I go about doing this?
you spawn the server like this
const serverProcess = spawn("./bedrock_server", { stdio: ["pipe", "pipe", "pipe"], cwd: "./server" })
then you just write into its console
serverProcess.stdin.write(command + "\n")
\n is just like an "enter"
and ofc you need to also log the std out with
serverProcess.stdout.on("data", (msg) => {...})
im getting an error with spawn not being defined, is there something is there something i need to import into the script? or is there somewhere specific i need to put this?
this is node just so you know
and yes
doesnt your editor autocomplete it tho?
import { spawn } from "child_process";
o
if you are just gonna use the /transfer command as an operator, so no scripts or anything you could also just set the op-permision-level to 4
oh, i've just been using scripting from behavior packs
am i able to do it from there, or should i use node
nope
well i wanted it to run from a button in a menu
yeh so this is kinda shit
so you need a parent process over bds that listens for http requests and then you send the command with the server-net module
if you don't know any of these thech then it might be difficult for you
yeah im very new to all this stuff
would it be better to switch to using node for this to work
you have to use both
look
our goal is to write a text into the servers console directly
alright
should i like setup what you said with node and trigger the function with my previous scripting?
you have to send a http request to the node process
ill try to figure this part out on my own and if i cant figure it out ill come back
system.runInterval(() => {
world.getPlayers().forEach(player => {
if (player.hasTag("islandGen")) {
const startLocation = getIslandData()
startLocation.x += 100
startLocation.z += 100
let newLocation = startLocation
setIslandData(newLocation)
player.runCommand(`tickingarea add circle ${newLocation.x} ${newLocation.y} ${newLocation.z} 4 test`)
system.runTimeout(() => {
newLocation.y += 4
world.getDimension("overworld").setBlockType(newLocation, "minecraft:dirt")
}, 1)
system.runTimeout(() => {
player.teleport(newLocation);
player.runCommandAsync(`tickingarea remove test`)
}, 10)
}
})
}, 400)
So like the gen works, but it bugs out and errors like this, can anyone help? And also it’s suppose to be a structure, but not even a dirt block will work.
Hmm, hard to tell why it's saying chunk error, but I would make sure your coordinates show whole number no decimal
In case that's messing up the xyz
Almost seems like your tryn to access a different chunk some reason
I’m trying to generate the "islands" 100 x away and 100 z away every island
And it can’t be decimals
Maybe add a ticking area before generating those, and then remove the ticking area after
This does that
I do everything on mobile 
Geez
This didn’t take too long but still a pain I had to download and fix the extensions for each icon
Wow very nice
Thanks
with the custom item components, is there a way to store data on a component? I would like to store some integer values that my script can use, and I cant seem to figure out if there is a way
Wdym store data on the component?
most components I see can store something, like "minecraft:max_stack_size", or the shooter component, and I would like to do something like that
Ah so parameters
Unfortunately, there is no way currently. You can use tags like i did: https://github.com/SmokeyStack/adk-lib
ah that sucks lol, thanks, I will have a look at that 👍
How do I resolve the issue where beta server and server-ui modules aren't working together properly?
error TS2345: Argument of type 'import("C:/.../node_modules/@minecraft/server/index").Player' is not assignable to parameter of type 'import("C:/.../node_modules/@minecraft/server-ui/node_modules/@minecraft/server/index").Player'.
In your package.json add an override key
Oh shoot, I forgot about that
#1067535608660107284 message
Thanks
which one is better in general, Date.now() or system.currentTick?
gotcha
does runTimeout run exactly after 50 millisecond, or does it depend on server tick?
world.getPlayers().forEach(player => {
player.addTag('${all_tags[world.getTimeOfDay()]}')
})```
For some reason when I'm putting ('${all_tags[world.getTimeOfDay()]}'), the script stops working. It starts working again after specifically removing [world.getTimeOfDay], is there any reason for this? Also should I make a full post for this or not, I'm on the fence.
It does depend on server latency, yeah
rip
i cant think of any other way to pass damage value from entityHurt to entityHitEntity 
You can definitely store their health into a property and check for a change with an entityHitEntity event
i switched from currentTick to Date.now() and using a tick is unstable now
Still confuzzled
basically uh
i have an entityHitEntity event that fires a function
and the function gets damage from entityHurt
it needs millisecond precision but
_ _
Why is it that precise?
im making weapon cooldown (and bypassing iframes)
but uh
yeah, its buggy because of how tick works
I always just recommend setting health directly for bypassing iframes
i do that too but
its not just about bypassing iframes, the weps have special abilities too
Is there a link where I can learn AddItem?
that file has nothing to do with addons right?
no
try nesting the event?
entityHitEntity.subscribe()
let damage = 0;
entityHurt.subscribe() //get damage here
entityHurt.unsubscribe()
wouldnt that be laggy
just wondering
idk.
one way to find out
actually, I think it would be better with async yeah
let damage = await hurtDamage();
async function hurtDamage() //promise that returns the damage from entityHurt if it fires. Otherwise 0
oh yeah uh
i did a test with Date.now() to get the delay in setTimeout without delay defined and
it somehow returned 0 or 1ms
Intended design.
entityHurt called after the game checks for iframe and calculate the damage. But entityHitEntity can run straightaway because there's no other operation at that time frame
i always thought it was just because of event order
who knows. that was just my assumption. ^
Does Additem work with TypeScript?
Yeah
you have to compile TS files to JS
How?
Is there a video about this?
It should say scripts/main.js.
You write the code in TS for development but compile it to JS for testing or distribution.
Do I need to download an app to compile?
You know... you don't have to code in TypeScript just so you can make addons
No, VS Code is capable of compiling it. You just need a file called package.json which targets a set of dependencies needed for your build environment. Then executing npm i in the terminal from VS Code will grab those dependencies listed in the file.
how did it go from addItem() to TypeScript xd
I write code with my phone
.
In that case, stick with JS. You have very little resources available on Mobile to help manage a build environment constructed out of TS. What few methods are available may be too complex for you. I believe @woven loom has a post somewhere that does show how to develop using termux with straightforward instructions but I'm not able to find it at the moment.
But I need to use addItem
You do not need TS to use Script API.
But
TS is only a superset of JS.
What kind of "addItem" here lol
the method, or a custom function
This is why I tried Ty
.
addItem method from the Container class works with JS too
For clarification, TypeScript is just modified JavaScript for development. It'll get compiled into plain efficient JS, so basically just JavaScript with extra steps
I understand
Here's an example of using addItem() to give iron sword with its 40 of its durability used
const inv = player.getComponent("inventory").container;
const item = new ItemStack("minecraft:iron_sword",1);
const durability = item.getComponent("durability");
durability.damage = 40;
inv.addItem(item);
Giving it unbreaking 3:
const enchantable = item.getComponent("enchantable");
enchantable.addEnchantment({
level: 3,
type: new EnchantmentType("unbreaking")
});
Edit: OH wait I did it with an s 💀 There, should be addEnchantment for single instance
Thanks
Do I need to addEnchantments when adding multiple enchant?
addEnchantments([
{},
{},
{}
])
import that EnchantmentType
Ok
can't you just
{
type: "unbreaking",
level: 3
}
```?
Hm
owh you can't
What
Does anyone know if its possible to disable trident riptide collisions?
Maybe editing player.json
And triggering event in script
But, what are the conditions to assume that the player is flying with riptide? 🤔
hey guys, is there a way i can make a structure generate in the world using structureManager just like with feature and feature rules?
i really need help on this one bcs im really new to structureManager and i want to understand how it works
why do you want to do it in scripts
I mean there's probably a way but... I dont see the point if features are functional
bcs my structure is really big, i think 50+ by 50+ blocks (x, z), and when it generates, it doesnt generate fully, even in i set "x": 0 and "z": 0 in feature rules, its still cut of
i think mmax structure size is 64 by 64, but my structure is smaller then these sizes, so its quite a problem for me
I may have a solution.
also, it generates under ground
you can make a block/entity that gets placed and it spawns the structure instead.
so you could just use a single block feature.
orrrr, use a command block with /structure command
#1067869232395735130
anyway, ive got a soultion, thank u
i mean, with the command block
Is that bettet than natural generation? Natural generation also replace blocks
instead of making custom block/entity, i'll just make it with command block
I mean world generation*
and how would you make the command block disappear
with the command block itself?
lol
ye
cool
I have an idea on how it will be
alr
I've done this before, having the natural world generation create a structure with a command block that sends scriptevent namespace:structure structureName. Then respond to that scriptEvent by deleting the command block and placing a structure.
Only problem I ran into was that if the structure I wanted to generate was too big then I had to manage ticking areas and waiting for the whole area to load first.
But I think structureManager takes care of that for you now?
Nope
Chunks need to be loaded too
It throws an error if you try to place a structure ouside the world boundaries
Please read the documentation https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/structuremanager?view=minecraft-bedrock-stable#place
That's an entirely different situation. That error would get triggered if you tried to place a structure outside of the Y range of the dimension.
In fact, I just tested it and it does work correctly on unloaded chunks, as the npm type definitions say:
Nice, thanks
that's interesting
maybe we can fill unloaded chunk with that
Looks like nobody read this before?
Is it possible to make a custom event with subscribe and unsubscribe methods?
yes
how do i?
like, i am making a onPlayerJump afterEvent
i have the code for it, but can't make it a callback
and i dont know how to make it have subscribe and unsubscribe methods
things like that already exist, maybe take a look at them to see how they did it:https://discord.com/channels/523663022053392405/1254305318196871269
i already saw it, but i want to do it a different way
can you write code for me, for making custom event callback?
i want to see how you do it your way
anyone got the new npm for the update?
@still rampart
please
Is the most current (stable) version of server API 1.11.0 and server ui API 1.1.0?
@minecraft/server - 1.13.0
@minecraft/server-ui - 1.2.0
Update came out earlier.
Ah, thanks for letting me know
No problem
Can anyone tell me what’s new
Stable scripting addons go brrr
Is Minecraft debugger diagnostics working now in latest stable?
It should, yes.
function testmenu(player) {
const modal = new ModalFormData();
modal.title("");
modal.textField("text", "...");
modal.show(player).then(result => {
const data = world.getDynamicProperty("st");
const st = JSON.parse(data);
st.push({text: result.formValues[0],
n: player.name
});
const stJson = JSON.stringify(st);
world.setDynamicProperty("st", stJson);
})}
Not work, why?
Anyone here able to help me with my post?
new update has broken some things Im not quite sure on how I fix it
Check the variable st to see if it's defined after getting the dynamic property.
You can print it to console.
how do i fix items?
Anybody know how to get the dynamic property of an entity that died? Seems like there's no before world event for entity die...
This is happening because no data is recorded. I don't know how to do this.
Does the afterevent not work?
Well It looks like it can't read the entity's dynamic property after death
The entity has to be loaded.
I know that...
Im going for a different approach either way. So thanks for the 'help'
If loaded, it should have no issues reading the dynamic property. Could you explain in more detail or share some code?
It would make sense though since the entiy not longer exists it frees up the proeprty
Which means the entity is not loaded.
Help pls
Yeah? Are you reading the same conversation as I am?
Then you need to find a point in your project where you set the dynamic property so that when you get it st will be defined.
Lol, about the dynamic property from NG_Web?
Yes...they're trying to read it from a dead entity...which isnt loaded...which is why i said it frees up the property bc the entity no longer exists
Can you give me a sample code please?
Yes, I was only reaffirming this because of what I said to the individual just before that.
Y'all are making it a bigger deal than it is, I was only asking for a different approach
🤦
To see the other things before its tamed
tamedToPlayerId
tamedToPlayer
is useless then?
And isTamed
is this a bug?
Works as intended since once its tamed you dont need that component anymore
so those should be moved to different component no?
what would be the best way to kick a player out of a server form?
i should've clarified i wanted stable
welp
welp
You could just crash their game 😈
Welp
why does this component not working for player?
world.beforeEvents.worldInitialize.subscribe((data) => {
let { blockComponentRegistry, itemComponentRegistry } = data
blockComponentRegistry.registerCustomComponent("ct:pressure_plate", {
onStepOn: ({block,dimension,entity}) => {
dimension.runCommand("say On")
},
onStepOff: ({block,dimension,entity}) => {
dimension.runCommand("say off")
}
})
})
what is alpha?
New version, not useable yet
oh. so i cant actually set my pack to that version?
Yep
😦
what's the latest version of the stable api?
1.13
thanks
Guys, quick question. I'm new to Mc scripting, and I'm looking for a resource where I can see what are te current features in the latest stable API version. To be specific, I'm looking for a web to learn things like how to get the player's position in a specific moment, or how can I add/remove tags from items when used, and things like that. I mean, something that explains what can be done with scripts today. The documentation I've found in the MS Learn website wasn't that helpful. If you guys know anything else, please let me know
@granite badger @obsidian coyote @honest spear How much examples do you have guys, Jayly are your examples online onbyour docs
you need to get started with script api first
once you do, all that stuff is as simple as
player.location
player.addTag("tag")
player.removeTag("tag")
there is a lot more then just that
assuming you have some JavaScript knowledge the wiki is a good place to start
https://wiki.bedrock.dev/scripting/script-modules.html
once you have basic idea on how to use script api you can check the docs for all the properties and functions and methods available
official docs:
https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/?view=minecraft-bedrock-stable
jayly docs (have more examples and easy to use):
https://jaylydev.github.io/scriptapi-docs/
stirante docs (have some stuff the other docs don't):
https://stirante.com/script/
I found Jayly's website, which I think is clearer than the official documentation
For instance, I knew about player.location, but I couldn't find anything related to it the official documentation
It may be there somewhere, but it isn't easy to find (at least not for me)
you are looking for a player property so you need to find the player class
all his properties and functions will be listed there
const system = server.registerSystem(0, 0);
system.initialize = function() {
this.registerEvent("minecraft:entity_started_riding", this.onPlayerLanded);
};
system.onPlayerLanded = function(eventData) {
let player = eventData.entity;
let playerPos = this.getComponent(player, "minecraft:position");
let playerOnGround = this.getComponent(player, "minecraft:on_ground");
if (playerOnGround.data) {
// Player has landed on the ground
this.broadcastEvent("minecraft:execute_command", "/function your_function_name_here");
}
};
Can someone help me how to put this into JavaScript Import?
https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/player?view=minecraft-bedrock-stable#properties
I think that's the website for the player class, right? But I don't see any "location" property there
export function functionName(...args) {
}
}
I may be looking at the wrong place...
Exactly. I couldn't find it on the official website, but I've found it on Jayly's site. That exactly what I was talking about with my first post
weird
maybe because of this?
entity class dose have it
if you cant find something in Player class, you should also look for Entity class
its usually there
Idk. Maybe they just show you the property in one class, but if it's shared with another class, they won't repeat it. That might be the reason I found that website not so beginner friendly and started looking for another resources 😅
most of us don't use the official one for many reasons
what are the stuff that moved from preview to beta?
Can relate
So Jayly's should be the one to go to
from beta to stable?
ig you could say that too
from preview to beta in stable
Read the changelog lol
i could but
i mean all the api preview stuff get to the stable beta api
😔
@shy leaf
potions api thing
removed old items from MinecraftItemTypes
added some other enums types
and a lot of stuff moved to stable
yep
and the ui lib 1.2.0 is stable now

sumonable wind charge
and the camera orbit thing is no in the api
imma go try this NOW
alr have fun
how do i convert this to scripts
?
so the events still work?
yes
YESSSSSSS
entities are not changed, besides run_command being remade into queue_command
ye
omfg i thought i was bouta go thru a midlife crisis
ive already had 1 of those today
but I mean you could probably move whatever is activating those events to scripts anyways
i know, but i want clicks to open npc's not punches
didnt they remove it?
no?
It's still a beta APIs thing
Oh
ah ok ty i used a stable version lol
@distant tulip we have got a problem....
getBlockFromViewDirection, gets the block from the view direction... not what block the player is aiming at.
function getAdjacentBlock(face,block) {
switch(face){
case"Down" : return block.below();
case"Up" : return block.above();
case"East" : return block.west();
case"North": return block.south();
case"South": return block.north();
case"West" : return block.east();
}
}
What does this Unknown block during Deferred BlockDescriptir resolution error means?
that's not what I meant
Welp
i mean for mobile players, if they don't use cross hair, the block they are interacting with isn't the block they are facing
Yeah, hmm
so playerInteractWithBlock is still needed after all
Well, maybe that's on purpose? Use blockintwrqct at that point?
Oh lol you said it
View vs actual interaction
yeah
maybe make your own ray
from player head to the block location
nvm that won't get the exact face
hmm
itemUseOn is the only option i think
if only getBlockFromCursorDirection() 
if only interact with block stable
https://cdn.discordapp.com/emojis/1016595573371064330.gif
that won't work and you know why
yeah
well, i guess i will sacrifice the mobile players 
I hate mobile too, dw
Separate UI 
Bad cursor (see above) 
Item use & block mine are same button 
no swing on air
maybe a combination of both playerHitBlock and ItemUse will do the job?
but how do i get the event to not fire twice (because as Herobrine said, item use and block mine is the same button)
cooldown
I was just referring to the fact that they can't "use" an item, it was a problem I ran into with my addon
Only works on the new controls
won't they fire at the exact same tick?
probably not
didn't run into that problem tbh
i mean for mobile players, if they start using the item they will also hit the block
Force them to use split controls schema
settings isn't something you can change by addons
Im aware
more like tell them to change it
Did I say to use via addons? Im saying as a suggestion in your addon description or on player join, tell them to use split contrl
- I won't use split controls myself, it's horrible
I love split controls, love the crosshoair
the cross hair is fine but the forced joystick instead of movement buttons is way too dangerous
all my scripts are broken hip hip hooray
There's a toggle to activate split control without changing the movement method.
could anyone tell me what this means?
[Scripting][error]-Plugin [Extended v0.1 - 1.0.0] - [main.js] ran with error: [SyntaxError: Could not find export 'BlockVolume' in module '@minecraft/server']
It could not find the export BlockVolume in Minecraft/server
If you can't find something which you think should be there check the extends at the top of the docs. All entities have a location, so it's a shared property on entity rather than just being on player 😀
idk what that means, I'm really new to scripting
The text: BlockVolume
inside your: import { world, BlockVolume } from "@minecraft/server";
You should learn basic JS first before doing ScriptAPI
understanding the error helps debug your codes
how would i convert this command using the removal of hcf stuff because i dont understand the docs at all
what is waitTicks for and whats the difference with runTimeOut
is that block, item, or entity json?
block json, i opened a post also
use custom components https://learn.microsoft.com/en-us/minecraft/creator/documents/customcomponents?view=minecraft-bedrock-stable
i stated in my post ive read the docs but still dont understand
Where do you suggest I start?
From
"modern JavaScript" website
As the Script API is a framework built on JavaScript code, having an understanding of JavaScript is key.
If you are being shown this, then you most likely are a beginner with JS and could use a little guidance.
Videos on Learning JavaScript
Javascript in 1 hour
Javascript Classes in 1 hour
Web Guide:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide
Reference Sites:
https://www.w3schools.com/jsref/default.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
https://javascript.info
how do i use Difficulty enum?
Currently theyre in here https://github.com/JaylyDev/ScriptAPI/tree/jayly/examples/examples. The workflows aren’t setup yet so it’s subject to change
Bro really ping himself
GameModes
Import it from server module
And
GameModes.survival
Or idk
uh like
They are just the survival type id
for checking (if difficulty) or whatever that
On objects
Difficulty lol not Gamemode
My bad
Hmm , idk if that possible
I mean to detect teh difficulty
The only thing u can detect
If world is on hardCore mode
Or not
Anyways
@shy leaf
U use them the same way
Difficulty.hard
Or
Difficulty.Hard
- one of them
easy
etc...
U import it
From server too
@shy leaf The only thing I found in the docs is to use an entity: https://learn.microsoft.com/en-us/minecraft/creator/reference/content/entityreference/examples/filters/is_difficulty?view=minecraft-bedrock-stable
import { Difficulty} from "@minecraft/server"
Do you even know what "Enum" are?
Yes ,
ok
They're like chocolate bars with caramel inside :3
I get this error but “minecraft:tick” component doesn’t seem to exist
or is it beta?
nvm im stupid
It is possible to obtain water or lava with getTopmostBlock?
do u love mc
function createauction(player) {
const inventory = player.getComponent("minecraft:inventory").container;
const form = new ActionFormData()
form.title(`s Inventory`)
form.body("")
form.button("§cBack")
for (let i = 0; i < inventory.size; i++) {
const item = inventory.getItem(i);
if (item == undefined) continue
form.button(inventory.getItem(i)?.typeId + i)
}
form.show(player).then (result => {
if (result.selection === 0) {
auction(player)
}
if (result.selection !== 0) {
console.warn(inventory.getItem(result.selection-1)?.typeId)
}
});
}
Why is this happening?
content logs
What
but from what i can see, continue is the issue here
its for loops
could someone help me with this
world.beforeEvents.playerBreakBlock.subscribe((e) =>{
const {block, player, itemStack, } = e
if(!player.hasTag("verify") || !player.hasTag("member")){
e.cancel = true
system.run(() =>{
player.sendMessage(`your SMP >> §cyour currently a non verify member, so ask a admin or owner to be able to verify you`)
player.playSound("random.break")
})
}
})
even though i have the member tag i cant do nothing?
he has them on
The console message should say the name of the item I selected, but it says undefined
it checks "if the player does not have verify tag OR if the player does not have member tag"
my eyes saw the log appearing but my brain thought the content log was off 💀
whoopsie
i have the tag though
well the member one
whatcha trying though
if i add && then i would need both
players without those tags cant break nothing
very simple so idk why i am having problems
if (!(player.hasTag("verify") || player.hasTag("member"))```
oh
i thought you would need to add the ! on both statments
well youre using ||
true
you want it to check if the player doesnt have any of those tags, right?
yes
|| returns true if any check inside is passed, and ! reverses that
so this returns true if the player does not have verify or member tag
if the player has any of those, it returns false
cheers
Returns true if they don't have verify or if they have member. The second condition isn't negated with !
its wrapped up with ()
What
understandable
Snuck past me haha
I would probably write it like this since it would be easier to read, but this is purely a preference here.
if (!player.hasTag("verify") && !player.hasTag("member")) {
};
thats better
Less operations also. The other one would have to check both conditions before determining if ! returned the condition to be met. That one checks for one, and if it doesn't exist then it just stops and moves on. The second condition won't be looked at unless the first one returns true (that is, they don't have it).
.
Help pls
What exactly are you trying to accomplish? Your code looks fine. Could be an issue related to the function you are calling.
The console message should say the name of the item I selected.
Because there is a button called back
1 or 0 I presume so let's assume it's 1. You are targeting 0 because you are checking for (1 - 1).
Yea
But 0 isn't what you selected. You selected 1 in that example so why would you check 0.
Does that make sense?
for (let i = 0; i < inventory.size; i++) {
Here i is the slot of the player's item
I'm talking about the line where you print console.warn().
Remove -1 from result.selection and see what it does.
function createauction(player) {
const inventory = player.getComponent("minecraft:inventory").container;
const form = new ActionFormData()
form.title(`s Inventory`)
form.body("")
form.button("§cBack")
for (let i = 0; i < inventory.size; i++) {
const item = inventory.getItem(i);
if (item == undefined) continue
form.button(inventory.getItem(i)?.typeId + i)
}
form.show(player).then (result => {
if (result.selection === 0) {
auction(player)
}
if (result.selection !== 0) {
console.warn(inventory.getItem(result.selection)?.typeId)
}
});
}
function createauction(player) {
const inventory = player.getComponent("minecraft:inventory").container;
const form = new ActionFormData();
form.title(`${player.name}'s Inventory`);
form.body("");
form.button("§cBack");
const itemButtonMap = []; // Array to map buttons to inventory indices
for (let i = 0; i < inventory.size; i++) {
const item = inventory.getItem(i);
if (item == undefined) continue;
form.button(`${item.typeId} ${i}`);
itemButtonMap.push(i); // Store the inventory index for this button
}
form.show(player).then(result => {
if (result.selection === 0) {
auction(player);
} else if (result.selection > 0) {
const inventoryIndex = itemButtonMap[result.selection - 1]; // Adjust index
const selectedItem = inventory.getItem(inventoryIndex);
console.warn(selectedItem?.typeId);
}
});
}
That should work now that I see what you are actually trying to do.
Work
Thanks
why am i getting a error from this
world.beforeEvents.itemUse.subscribe((e) =>{
let {source, itemStack} = e
if(source.hasTag("mod") && itemStack.typeId === "minecraft:totem_of_undying"){
source.sendMessage(`§l§dyour SMP >> §aWelcome staff member`)
verifyMenu(source)
} else {
source.sendMessage(`§l§dyour SMP >> §cYou do not have access to staff tools`)
}
})
function verifyMenu(player){
const menu = new ModalFormData()
.title("Enter players name for verify")
.dropdown("Players")
.submitButton("submit")
menu.show(player).then(e =>{
})
}
what error
nvm i did the .dropdown wrong
What exactly do you want to do with dropdown?
i wanted to get all players name
but i fixed it
i fixed it
function verifyMenu(player){
let playerNameList = Array.from(world.getPlayers(), plr => plr.nameTag);
const menu = new ModalFormData()
.title("Enter players name for verify")
.dropdown("Players", playerNameList);
.submitButton("submit")
menu.show(player).then(e =>{
})
}
Try this
i did
const players = Array.from(world.getPlayers());
const playerNames = players.map(p => p.name);
Was this in your code?
yh
are blocks typeid and item typeid usually the same?
Both of them have minecraft: at the beginning
not the namespace
like cobblestone item and cobblestone block
those are same
but im not sure about other things
Probably not
hmmmm
@shy leaf
hello
Minecraft:daylight_dedector
Daylight sensor
You dont need array.from lol
why
is that goodie?
thats Spy
It doenst do nothing in this case
from TF2
Array.from copies the array, you will use it in very specific cases
But this is not one
cant you just do
world.getAllPlayers().forEach(p => {
//code
});```
oh wait
player names
🗿 nvm
Is the same anyways
hey, does everthing moved to stable?
https://stirante.com/script/diff.html#%40minecraft%2Fserver/1.13.0/1.15.0-beta.1.21.30-preview.22 The following are still in beta
const playerNames = world.getAllPlayers().map(p => {
return p.nameTag
}
there we go
@rigid torrent
That’s me
the template of log doest work properly
it doest allow log to be placed on each other
That’s a custom components issue
I thought it would be fixed on this update 🤔
Well yeah, that’s not an issue in the template
When Mojang fixes it, the template will automatically be fixed too
You can, however, fix it yourself by cancelling the interaction and place the block instead
No, all of my templates are on my repo
hm
which interaction
also "tag:wood": {},
how does it work
The one that triggers incorrectly
no error in log
That’s just to identify the block as a wood, you can call it whatever
Because is not an error of the code
I don’t quite understand
like mining speed
almost all axe work at same speed
also the leaves template works as a solid block when placed of water it cancels the water source
You can change mining speed at your own liking
We don’t have a proper way to waterlog blocks yet, so that’s intended
remember:
! ( X && Y ) == !X || !Y
! ( X || Y ) == !X && !Y
@glacial widget
Change it to :
if ( ! ( X || Y ) ) {
}
yeah i did that and it worked
thanks
UW
Ok then
Is there a 2.0 alpha for the Minecraft-server-form module?
Maybe, doesnt matter since it isnt useable
Realms dont work 😦
how to detect if the villager is baby?
Yea, saw people reporting issues after the update. Bots/Scripts that try to communicate to the servers are also panicking.
BDS works though lol.
entity.getProprety
can i ask a silly question about js?
I must be blind cuz i can't find custom entity components docs
there isn’t such thing
So is there any way to run scripts when an event triggers for an entity
Yes
Documentation for @minecraft/server
I thought they did something to datadriven stuff or was that just blocks and items (or maybe i just misremember stuff)
getComponent("durability").damage;
By using this, I can find out how much damage the item has taken, but is it possible to find out the max durability of the item?
Yes, read the docs
Any chance you can post a link?
Documentation for @minecraft/server
Beta
https://stirante.com/script/server/1.14.0-beta.1.21.20-stable/classes/ItemDurabilityComponent.html
Documentation for @minecraft/server
I found it to be very simple
where is the docs for minecraft:tick?
I don't see it. Just tick_world.
👀
Is there an equivalent of getItemStack but for entities? I want to save all the data of an entity to be able to spawn another of the exact type (name, HP, inventory, etc.).
Idk how good you are with programming but everything is object oriented, so the players position will be on a Player object class. Then you need to get that player, but more on that later.
2nd thing we have events for basicly everything that changes within the world. If theres no event for something theres probably no way to handle it.
Theres events for things like blocks being changed, and interacts where player clicks a block or entity with left or right click. Usually everything leftclick has 'hit' in it. And then theres more events but thats rather straightforward once u look at them
3rd thing is actually interacting with the world itself. This is either done by interacting with the global 'world' (which you can import) or on the respective Dimension class (you can get that through the world object or on any entity the dimension property)
On here you can change blocks, run commands, teleport and change, get entities and so much more. Everything you want to do to something you do it on its entity object, sometimes theres universal functions for all of them, but uncommonly so youll have to loop through all entities
I think this should be sufficient to get you going 🙂
hes questions has been answered already
Also, what's the difference between a property and a dynamic property?
And thats because Player actually inherits all properties and functions from entity, for some reason all those functions are never listed in player themself. In that case you might need to go to the top of the page where it links the classes for inheritance
no
you need to go through all those and map them to an object
save them into a structure then load them 🥴
Im not trying to catch a fish for him, Im trying to teach him how to catch fish on his own. That was my try at that
And the responses he got whree the first thing imo
🤨
Thats a metaphor
So u wanna an event to detect fishing ?
Very different actually. A property likely refers to the javascript property, here, every member of an object is a property. So player.location is a property and in player.location.x, x is the property of location and location is the property of player.
Is entity property defined in entity still not removed?
XD , bro was gonna explain oop for him
Like from the bee? Or wait imma read what entity perms first, me is confused
properties are from the entity json file
you can't add properties or remove them and the data need to follow the range the property have
dynamic properties dose not have anything to do with the entity json
you can save dynamic properties to the world or entities or unstackable items
the data type is either number vector3 string or boolean, they are unlimited but each dynamic property can only store 32k bit
-
property (JSON) = Needs to be defined within the entity JSON. Accessible with Molang. Universally accessible by all packs. Has 1 tick delay for property update.
-
property (JS) = see #1067535608660107284 message (Does not save values across game session)
-
dynamicProperty = Created by ScriptAPI. Can only be accessed by ScriptAPI. Have more flexibility for storing values. Can be used even in beforeEvents. Updates instantly in that same game tick. Less possibility of conflicts with another pack.
odd
Dynamic properties on the other hand are a way to permanently store information on the player or whatever. You see we basicly get an disguised object, when we are dealing with the player class e.g. thats just a representation of the player from the actual internal minecraft player class. So you would be able save data by doing something like player.jumpscareCount, but you cant because the player object is kind of not a real thing, and even then it would only temporarely save and when you close the game, all the info will be gone.
Dynamic properties store all the data indefinetly on that thing you tried to set it on.
@grave thistle
And then there are actor properties, who are actually more connected to animations and the entity.json files, basicly a way to store info when dealing with entities in animations and entities
Thanks for all the replies. I've used dynamic properties a lot, just never normal properties
They're useful for communication between the resource pack & the server 
Can the same DynamicProperty be accessed from a different pack? Or it's exclusively unique for each pack?
Saved on it? no
uuid is just a "reference"
Can't wait other peps showcase their projects or addons using scripts and stuffs with scripting api being stable
Helllooo, are the block components. on_placed, on_player_place etc, deprecated, are they entirely replaced with cusotm components?
I created a block that when I interact with it, it makes an event, but how do I make it work without caring about the item I have in my hand? I put undefined but it only works when I have an empty hand.
Beta
https://stirante.com/script/server/1.14.0-beta.1.21.20-stable/interfaces/BlockCustomComponent.html
Stable
https://stirante.com/script/server/1.13.0/interfaces/BlockCustomComponent.html
Documentation for @minecraft/server
Documentation for @minecraft/server
I would like it to work with any item not just empty hand
Latest NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Beta APIs NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Preview Latest NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Preview Beta APIs NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
@granite badger any chance you can just make this a drop down or smthng. It is quiet big
just don't check the item
in this case instead of putting undefined keep it empty?
I think you have something like
if(item...) {
// code
}
just do it
// code
Thanks
ended up being in one of my scripts was literally just "vector" (fyi im not an idiot, it did not show in the search 😭 )
Can I just use 'invisibility' for .addEffect or do I actually need to import the minecraft effects list?
Also, is there a way to register multiple item custom components in one function?
You can use invisibility. It accepts strings.
Figured as much, just making sure
Whenever in doubt, just double check at https://stirante.com/script/server
👍
Is it possible to use Additem for a slot?
Latest NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Beta APIs NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Preview Latest NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Preview Beta APIs NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Hey I may be missing something simple, but how can i set a block property? So that my block permutation can change states based on that property. Nothing like block.SetProperty exists right now /if ever?
Use block permutation
block.setPermutation(
block.permutation.withState("state:name", value)
)```
Cool thank ya, how about if i want to GET a property / current state?
block.permutation.getState("state:name")
can we get the equipment of an armor stand? this doesn't work on armor stands for some reason js const head = entity.getComponent('minecraft:equippable').getEquipment('Head')
it works on the player tho
Guys is custum components for items like for replacing on_use broken or somthing on 1.21.20 version? Bc as i got informed this update have lot of bugs and problems
getEquipment don't work on entities
Hey so im trying to pass the players rotation to a block, via molang. instead of script. if possible.
Getting the state isnt quite working yet.
// Precise rotation of block when placed on `up` face
"wiki:rotation": {
"values": { "min": 0, "max": 15 } // An alternative property value syntax to define larger integer ranges easily
}
}
Basically I would like to call an event, which sets a property, based on the players rotation, through molang. like so:
"wiki:set_rotation": {
"set_block_property": {
// Now use the long Molang expression from before to set the rotation property
"wiki:rotation": "q.block_face == 1 ? { t.positive_head_rot = q.head_y_rotation(0) + 360 * (q.head_y_rotation(0) != math.abs(q.head_y_rotation(0))); t.block_rotation = math.round(t.positive_head_rot / 22.5); return t.block_rotation != 16 ? t.block_rotation; };"
}
}```
Because I have permutations that are reading this value. and changing locations.
``` {
"condition": "q.block_property('wiki:rotation') >= 4 || q.block_property('minecraft:block_face') == 'east'",
"components": {
"minecraft:transformation": { "rotation": [0, -90, 0] }
}
}
But as we do not have access to block 'events' anymore, and theyve been replaced by customComponents.
I have grabbed my block via the custom_component on_Place.
From here, since I have my block, i would like to simply fire an event, to set the players rotation. based on the molang, from above.
Am i able to somehow do this? I would just like to calculate players rotation, via molang, and set the rotation STATE with this value.
@wary edge 😄
why is bro pinging randoms
Hes admin and he helps almost every time lol
also off-topic
Is this from the precise rotation?
ik im saying ive seen people complain about getting pinged for helping instead of just asking ^^
im usign custom components, its not off topic
Id like to rgab it using molang if possible, seems easier than the scripting since its already there, and we just had access with events
You'll have to check the hcf-rewrite branch on the wiki github for now while we're attempting to merge it to the main site
There is no tool to directly translate from Holiday features to scripting?
i forgot about that 🤦♂️ is there a workaround?
@devout dune
world.afterEvents.playerPlaceBlock.subscribe((event) => {
const {player,block} = event
const {y} = player.getRotation()
const face = block.permutation.getState("minecraft:block_face")
if(block.permutation.getState("mba:head_rotation") === undefined) return
if(face == "up"){
let rot = y + 360*(y!=Math.abs(y))
rot = Math.round(rot/22.5)
rot = rot!=16?rot:0
block.setPermutation(block.permutation.withState("mba:head_rotation",rot));
}
block.setPermutation(block.permutation.withState("mba:show_head",true));
});
this what i am using in my head addon
(not using custom component sense i am supporting old version, you can easily switch to them)
depend
what are you trying to do
i think i can edit the armor stand file and make send script event message, but can we setEquipment for armor stands?
yeah, so setEquipment doesn't work as well
i think?
one second
alr
yeah, it doesn't
i guess i will resort to a scriptevent then
i am converting an entity event that turns zombie heads on armor stands into player heads when they are struck with lightning into a script
wait, can we detect it with commands?
that doesn't kill the armor stand?
testfor command with hasitem property
it does when it's a direct hit, not if i hit a lightning rod adjacent to it
oh right! but is it sensitive for data values?
there is amount and slot and data and location parameters
fantastic
Thanks! No way to trigger block event via script?
directly? no
Is there a way we could access a pet's owner info like playerName in scripting?
I'm trying to restrict a horse from being used by others except the owner.
you can using EntityIsTamedComponent
-# that don't work too
tameable component get removed on tame
mohamed elmakhloufi
To Do (Open)
Unresolved
What version is block.getRedstonePower in now? I'm trying 1.14.0-beta and I'm getting a "not a function" error
Documentation for @minecraft/server
Ah, thanks
Uhh, it's saying 1.15.0-beta isn't a valid version? this is strange, as getRedstonePower was available in 1.13.0-beta before, so I would've assumed it would have been moved to a version of the beta available outside of the preview edition
When teleporting an entity using teleport, is it possible to disable the smoothing on the entity's position when changing position?
Is there a way for two packs on the same world to communicate? I was thinking dynamic properties but I'm pretty sure those are per-pack, arent they?
They are per-pack, yes. You could use scoreboards, I guess.
Hmm
You could try doing something like player.__testValue = true and reading that in the other pack?
Like extending the player class?
I guess, yes.
That's an interesting thought
Just doing this, although it has no type definitions, is valid. I do it all the time in my packs for minor data passing.
Do you have an example?
if ((player.__tempCooldown ?? 0) > Date.now()) return;
player.__tempCooldown = Date.now() + 500; //Half a second of delay
Thanks. Will give it a shot when I decide make this change to my project
Mind you, idk if it can pass data between packs, but it's worth a shot
Yep
Hey, could you help me with this?
https://discord.com/channels/523663022053392405/1273416639345463407
couldnt find it
I can't remove block when it reaches 600 ticks from my block
import {
world
} from "@minecraft/server";
world.beforeEvents.worldInitialize.subscribe(event => {
event.blockComponentRegistry.registerCustomComponent("blc:dano_de_sangue", {
onStepOn: event => {
event.entity.runCommandAsync(`damage @s[family=player] 10 self_destruct`)
},
onTick: ev => {
ev.block.runCommand(`setblock ~~~ bone_block`)
}
});
});
Check your runCommand, its different from the other one you specified
wouldn't it be ev.block.dimension.runCommand?
it is not giving an error, but the block is not being replaced
use ```
${ev.block.location.x} ${ev.block.location.y} ${ev.block.location.z}
instead of `~~~`
nice!
thankys
can also do ev.block.setType('minecraft:bone_block')
I will prioritise and try to change this.
My block stopped working, can anyone help me? The log doesn't say what the error is
Unexpected version for the loaded data
when I use the component "minecraft:breathability": "air" the block works, is there any way I can replace this component?
@granite badger
Latest NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Beta APIs NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Preview Latest NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Preview Beta APIs NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
its working fine now idk what was the problem
sorry for pinging @wary edge, I have a question, what's the purpose of separating the anvil into 3 different blocks?
Since setblock command for anvil is now separated with 3 different anvil type blocks, and it removed the damage and direction for BlockState argument.
when you enter this unfinished command setblock ~~~ anvil [
it shows the available blockstate, which is only minecraft:cardinal_direction, and the other blockstate was "removed", although if you type ["damage"= you can still see available values for the damage blockstate.
idk if this was intended or not.
Purpose was java parity, iirc. They have separate blocks for anvil states (who knows why)
so when you break them you dont get a fixed anvil
thats my guess
I'll take your word for that one lol
i mean if they want it that way, they could've removed the other blockstate arguments functionality from the command, and BlockPermutation from the script api. 🤷♂️
is it possible to set bossbars to each individual player
ex: player names for each player
#1067869374410657962
what is deprecated anvil https://jaylydev.github.io/scriptapi-docs/latest/enums/_minecraft_vanilla_data.MinecraftBlockTypes.html#DeprecatedAnvil
anvil
they changed the anvils to have different ids
for broken anvils
anyone have a stable-version of isOp(), i can use?
Doesn't work :\. Tried this in one pack:
world.__proofOfConcept = 'Hello!';
And this in the other:
console.warn(JSON.stringify(world.__proofOfConcept));
Just shows undefined.
I have never tried that on world before, just on entity/plauer
I mean i'll give it a try on player too but I don't think itll be different
Does that mean the world objects are different for each pack?
use tags or scoreboard database
Does that mean the world objects are different for each pack?
definitely, each pack has its own environment
must be
that can break a lot of stuff
need some good IPC (inter-PACK communication hahah) here lol
Ik tags and scoreboards
scriptevent
Incase you were wondering, player also doesn't work.
Ah, good to know 👍
const enchantments = selectedItem.getComponent("enchantable").getEnchantments();
if (enchantments.length > 0) {
loreModifier = enchantments.map((ench) => `{
level: ${ench.level},
type: new EnchantmentType("${ench.type.id}")
}`);
function giveitem(player, itemid, amount, enchanted, loreModifier, durabilitydamage, durability, enclist, maxdurability, price, id) {
const inv = player.getComponent("inventory").container;
const item = new ItemStack(itemid, amount);
const durabilityy = item.getComponent("durability");
durabilityy.damage = durability;
const enchantable = item.getComponent("enchantable");
enchantable.addEnchantments([loreModifier]);
inv.addItem(item)
}
Why does it not work?
Everything works but enchant doesn't work
any errors?
if it's not enchanting the item, try this. I haven't tested it in-game
function giveitem(player, itemid, amount, enchanted, loreModifier, durabilitydamage, durability, enclist, maxdurability, price, id) {
const item = new ItemStack(itemid, amount);
item.getComponent("durability").damage = durability;
item.getComponent("enchantable").addEnchantments([loreModifier]);
player.getComponent("inventory").container.addItem(item);
}
try this
Ok
this is the exact same script lol
removing the variables won't change anything
they're passed by reference
i think his "loreModifier" is a string and not a Enchantment object:
https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/itemenchantablecomponent?view=minecraft-bedrock-stable#addenchantments
yep
Error
oh xp, my bad
The same
addEnchantments wants a Enchantment[] input not a string[]
Debug result for [code](#1067535608660107284 message)
Compiler found 0 errors.
ESLint results:
<REPL0>.js
1:10 error 'giveitem' is defined but never used @typescript-eslint/no-unused-vars
1:98 error 'enclist' is defined but never used @typescript-eslint/no-unused-vars
1:107 error 'maxdurability' is defined but never used @typescript-eslint/no-unused-vars
1:122 error 'price' is defined but never used @typescript-eslint/no-unused-vars
1:129 error 'id' is defined but never used @typescript-eslint/no-unused-vars
the object:
Enchantment = {
level: number,
type: EnchantmenType: {
id: string,
maxLevel: number
}
}
this error literallly says everything
But I don't know what to do
import { Enchantment, ItemStack } from "@minecraft/server";
import { Player } from "@minecraft/server";
/**
* @param {Player} player
* @param {string} itemid
* @param {number} amount
* @param {boolean} enchanted
* @param {Enchantment[]} loreModifier
* @param {number} durabilitydamage
* @param {number} durability
* @param {*} enclist -- what is that?
* @param {number} maxdurability
* @param {number} price
* @param {string} id
*/
function giveitem(player, itemid, amount, enchanted, loreModifier, durabilitydamage, durability, enclist, maxdurability, price, id) {
const item = new ItemStack(itemid, amount);
// change custom durability
if (item.hasComponent('durability')) {
item.getComponent("durability").damage = durability;
};
// add enchantmens
if (item.hasComponent('enchantable')) {
item.getComponent("enchantable").addEnchantments(loreModifier);
};
player.getComponent("inventory").container.addItem(item);
};
maybe this will help a little
i just like clarified the code kinda
remove all those unused params lmao
true, but i dont know if he needs them or not
eh ig
maybe in future he'll need them
ill send you a working code wait
Still giving error
All code
the error message would be better for understanding
uhhhhh
I've been dealing with this since yesterday and I'm about to go crazy.
maybe a better code structure would make it easier ro fix
can my bot help
Maybe
btw use this to create enchantments @fallow rivet
import { EnchantmentTypes } from "@minecraft/server";
/**
* @param {string} type
* @param {number} level
* @returns {undefined|import("@minecraft/server").Enchantment}
*/
function getEnchantment (type, level) {
const enchantmentType = EnchantmentTypes.get(type);
if (level > enchantmentType.maxLevel) {
throw new TypeError(`level of type enchant ${type}§r must be less than ${enchantmentType.maxLevel}`)
};
return {
type: enchantmentType,
level: level
};
};
just input type and level, will throw errors on invalid values
btw gtg, maybe jayly or some of the other users can help you, good luck
Debug result for [code](#1067535608660107284 message)
Compiler found 4 errors:
[36mmain.js[0m:[33m138[0m:[33m5[0m - [31merror[0m[30m TS2365: [0mOperator '>' cannot be applied to types 'string | number | boolean' and 'number'.
[7m138[0m if (price > 0) {
[7m [0m [31m ~~~~~~~~~[0m
``````ansi
[36mmain.js[0m:[33m197[0m:[33m40[0m - [31merror[0m[30m TS2345: [0mArgument of type 'string | number | boolean | Vector3' is not assignable to parameter of type 'string'.
Type 'number' is not assignable to type 'string'.
[7m197[0m if(data != undefined) {st = JSON.parse(data);}
[7m [0m [31m ~~~~[0m
``````ansi
[36mmain.js[0m:[33m214[0m:[33m39[0m - [31merror[0m[30m TS2365: [0mOperator '+' cannot be applied to types 'string | number | boolean | Vector3' and 'number'.
[7m214[0m world.setDynamicProperty("auctionid", auctionid+1);
[7m [0m [31m ~~~~~~~~~~~[0m
``````ansi
[36mmain.js[0m:[33m219[0m:[33m31[0m - [31merror[0m[30m TS2345: [0mArgument of type 'string | number | boolean | Vector3' is not assignable to parameter of type 'string'.
[7m219[0m const st = JSON.parse(stJson);
[7m [0m [31m ~~~~~~[0m
ESLint results:
main.js
1:37 error 'EnchantmentType' is defined but never used @typescript-eslint/no-unused-vars
77:17 error Empty block statement no-empty
93:17 error Empty block statement no-empty
156:1 error 'testmaxdurability' is assigned a value but never used @typescript-eslint/no-unused-vars
158:17 error Empty block statement no-empty
165:1 error 'testloreModifier' is assigned a value but never used @typescript-eslint/no-unused-vars
169:1 error 'testenclist' is assigned a value but never used @typescript-eslint/no-unused-vars
172:17 error Empty block statement no-empty
173:7 error 'testitemname' is assigned a value but never used @typescript-eslint/no-unused-vars
268:10 error 'giveitemm' is defined but never used @typescript-eslint/no-unused-vars
268:99 error 'enclist' is defined but never used @typescript-eslint/no-unused-vars
268:108 error 'maxdurability' is defined but never used @typescript-eslint/no-unused-vars
268:123 error 'price' is defined but never used @typescript-eslint/no-unused-vars
268:130 error 'id' is defined but never used @typescript-eslint/no-unused-vars
275:98 error 'enclist' is defined but never used @typescript-eslint/no-unused-vars
275:107 error 'maxdurability' is defined but never used @typescript-eslint/no-unused-vars
275:122 error 'price' is defined but never used @typescript-eslint/no-unused-vars
275:129 error 'id' is defined but never used @typescript-eslint/no-unused-vars
I'll try it later, if this is not fixed yet if I can help
IPC for command registry and callbacks 
anyonone got a action ui that to show inventory
According to official information from Mojang, the Holiday Creator feature will be officially discontinued in version 1.21.20 (or later versions), and triggers such as block or entity will be replaced by JavaScript. I have a question: Will entity models or block models still be kept in JSON format, or will they also be replaced by JavaScript? If they are replaced by scripts, how will the models work?
mojang discontinued HCF for a better replacement because they were accessible via experiments toggle only. models are stable already so there won’t be changes
Does anyone know how to setup the Dash compiler with VS Code?
bridge. is also good, but I would like to use the text editor I usually use
Can you post this problem as a post in scripting api channel? Or is this resolved?
what version did fix the ModalFormData scroll bar starting from the bottom?
umm, its the server_form.json isn't? not the script?
not really sure
as far as i know that is not something json ui can control?
yes it is, the script is just like the thing what to show and json ui is how it shows
i know it is not from the script
there is no property to control it
either it is hard coded or i am messing something
maybe you actually can, just need to make the thing inside the form less
@prisma shard do you have template for sapling
No resolved
@distant tulip not Hcf I want Scipt
#1273656649705586688
welp
help me I have a problem with my main.js nothing works anymore here is the error
[Scripting][error]-Plugin [real blitz kitmap - 1.0.1] - [main.js] ran with error: [SyntaxError: invalid redefinition of lexical identifier at main.js:210
]
this is my 210 line
function tpa(player) {
wtf sapling dont need script
@valid ice how do i use createPotion for itemStack
Does anyone know why my custom component is not registering?
excellentquestion
what even is this
custom components?
they are replacing block "events" and generic built in components like "on_player_placed"
yeah but
I like how beforeEvent playerPlaceBlock is beta, while the custom component for block: beforePlayerPlaceOn is stable.
anyone know why mine is not registering? did i set it up wrong
They forgor to release it out of the beta💀
my docs has examples there https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server_1_14_0_beta.ItemStack.html#createPotion
ty
@distant tulip
My log did not seem to fire at all. So worldInitialize is doing nothing rn? do i need to be in a different version..
o yea no nvm it doesnt have effect part
the id for effects arent working
i think its different for createPotion
they don’t use ids, again check examples (they’re hidden)
is the class even being created in the first place?
Yes sirrrr, the events im subscribing to right above it are working fine
"When" and "where" did you call it
beforeEvent worldInitialize needs to be called before the world loads. So subscribing in afterEvents scopes isn't an option
Please don't fish for help in other channels.
Sorry
my main ^Here is my main.js. simply creating an instance of another class. and invoking its initmethod.
Here is the constructor of the instance.
here's the issue: system.run() made it run the entire thing in the afterEvents scope. (basically waits for a tick)
At that point in time, beforeEvent - worldInitialize won't fire again. So subscribing after it won't do anything.
So i either need to subscribe, before system.run?
Or maybe something like this?
don't use system.run()
simple as that.
replacing this with just
'main()' wont absolutely break everything?
Isnt the point of system.run, to run logic on the server?
Yes? But it isn't necessary.
You can run the function without system.run
wat..
tyty
The main function
Of other programing languages
Isn't available
In js
U just write ur code
im confused, its a custom name
Oh ☠️
lmaoo
I thought u are java or cpp developer who wants to write script api ☠️
Other programming languages usually have this function called main that would be called for the first time ig
tbh i have no idea what im doing, hense why im in the discord everyday lmaoo
yea got it ty!
hey so im not sure yet if our system.run implementation is necessary (there are others working on the scripts) so id rather keep it as is, if possible.
Is there any other way to subscribe to beforeEvents.worldInitialize. With the current implementation?
for example, in another class, i am subbing to a beforeEvent. but then im firing system.run on the method. in order for it to validate.
If not, I can try to refactor to not use system.run! Just not 100% confident with it yet
The reason why the other works within system.run is because they don't immediately run, and can fires multiple times.
However, beforeEvent worldInitialize only run once, and you can't delay it even a single tick.
Yes, you can still use system.run to exit the beforeEvent/read-only scope. Just specifically, don't use it to delay worldInitialize beforeEvent.
okay ty, im understanding better. just not sure what you mean by, use system.run to EXIT the before event
I tried this
but this is obviously delaying it?
Yes, that's delaying the worldInitialize
though, you can add the other event listener inside the system.run
and this constructor is called during the first system.run call. here:
That's the second delay.
So around 2 game-tick
so what exactly do you suggest, instead of this
system.run(() => {
world.beforeEvents.worldInitialize.subscribe(e => {
console.warn("Registering custom component for placing corner light");
e.blockComponentRegistry.registerCustomComponent("ts_ml:on_placed", { onPlace: this.placeCornerLight });
});
});```
I'll say it clearly, put world.beforeEvents.worldInitialize outside any system.run()
Unfortunately i need it that clearly for now lmao.
I appreciate the help.
why? Is it because you need to wait for the creation of the subclasses?
Ill do some more digging and get back to you. I wasnt the one who implemented the initiation of classes, after system.run. And im not 100% sure yet what its been meant for
Technically, your code would still work even without the system.run
Yea i figured, not sure why exactly its been in place. I feel like we did have a reason. Maybe we needed the delay
Well, that makes sense, while working on a team sometimes someone forgets to check if it runs or breaks the previous code. xd
Anyway, I'm gone for the next 6 hours. Gotta sleep in my time zone.
kk thank ya dude, ill dabble with it!
Quick Note: Using system.run() makes you exit the "read-only" state. Within the "read-only" scope (beforeEvents listener), you can only retrieve and get values but are unable to modify the world. For example, using Entity.kill() would throw an error in the "read-only" state. Using system.run allows you to avoid this kind of thing. So, yes, system.run has its own merits.
hey guys
how do i make a money transfer script ?
Using @minecraft/server-ui and learning
function banReason(player, data) {
new ModalFormData()
.title("§b§lReason For Ban")
.textField("§c§lReason To Ban", "Type Here (Not Required)…")
.textField("§e§lDuration", "Duration In Seconds (Blank For Perm)…")
.show(player)
.then(res => {
if (res.canceled) return editPlayer(player, data);
let reason = res.formValues[0] || "Not Provided.";
let duration = parseInt(res.formValues[1]);
if (!duration) {
duration = 1000 * 19999999999;
} else {
duration *= 1000;
}
const banExpiryTimestamp = Date.now() + duration;
const formattedBanDuration = formatBanTime(duration);
const data2 = findUser2(data.playerId);
data2.banReason = reason;
data2.banned = banExpiryTimestamp
world.getPlayers().forEach(p => {
if (p.id === data2.playerId) {
world.sendMessage(`${p.name}`)
p.runCommandAsync(`kick "${p.name}" §c§lYou Are Banned.\n§r§cReason: §e§l${data2.banReason}\n§r§cDuration: §l§e${formatBanTime(data2.banned - Date.now())}`);
}
});
setPlayerData2(data2.playerName, data2);
});
}
yes, basicly when something is not defined it means its not defined
Words of Wisdom 😁
average script developer
so true
just got my first one of those 😂
hmmm tasty one
for how long i have to wait until decorators come to QuickJS native and darknavi updates the minecraft QuickJS engine?
10 Years or more?
Why doesn't it work?
{
"format_version": 2,
"header": {
"name": "test.5.0001",
"description": "test.5.001",
"uuid": "ba3540a0-baf6-415d-b42a-3f461c8514da",
"version": [1, 0, 0],
"min_engine_version": [1, 21, 0]
},
"modules": [
{
"type": "data",
"uuid": "470c5629-4ba8-4c6d-a2a1-c9d48c31aa7b",
"version": [1, 0, 0]
},
{
"type": "script",
"language": "javascript",
"uuid": "3f1f72b2-be67-4fde-a7b2-0efceee1dc82",
"version": [1, 0, 0],
"entry": "scripts/main.js"
}
],
"dependences": [
{
"module_name": "@minecraft/server",
"version": "1.13.0"
}
]
}
log?
I'm trying to start with the script, but I can't get the hello world to work.
import { world,system } from '@minecraft/server';
world.sendMessage("hello");
it is dependencies not dependences
thx{
