#Script API General

1 messages · Page 13 of 1

wintry bane
#

So where do I add it? the example doesn't say

#

also using "1.21.10" says it's out of range

#

im on stable version

wary edge
wintry bane
#

where do i put this

cold grove
#

Components, read the links

#

Where you think it will look prettier(?

wintry bane
#

Adding it shows this

subtle cove
#

did u do the scripting part?

wintry bane
#

yes

#

using the same format version shows this

wary edge
subtle cove
#

hmm, its in preview

wintry bane
#

so not in the stable ver

wary edge
wintry bane
#

the blocks work

wary edge
#

Jsut beta apis

wintry bane
#

is it on 12-beta or 13-beta?

chrome flint
#

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

glacial widget
#
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?

true isle
true isle
valid ice
#

You can turn off HCF on a world using a third-party editor

honest spear
#

ChestFormData is not native form

valid ice
#

Selection for pattern works the same as regular form

gaunt salmonBOT
#

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]
umbral scarab
#
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

valid ice
#

Entity cannot get equipment component

umbral scarab
valid ice
#

only way atm is using something like replaceitem reallysad

umbral scarab
#

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

valid ice
#

Can you show what you did?

umbral scarab
#

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.

valid ice
#

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

umbral scarab
#

May I see an example?

valid ice
#
entity.runCommandAsync(`replaceitem entity @s slot.armor.feet 0 ${boots.typeId}`);
umbral scarab
#

ohh I see what you mean now, I'll give that a try and let you know how it goes

#

tyty

umbral scarab
# valid ice ```js entity.runCommandAsync(`replaceitem entity @s slot.armor.feet 0 ${boots.ty...
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

valid ice
#

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

umbral scarab
#

location: player.location?

valid ice
#

If that's what you want, sure

#

Do note that the closest may be the player themselves, in that case

umbral scarab
#

I'll just add a family exclusion if thats the case 👍

#

got it working now thank you for the help!

valid ice
#

excellent!

true isle
valid ice
#

If you version your block & items they should not throw errors

#

I do not use HCF, and none of my custom stuff throws errors

true isle
#

Yeah that's ehat I was getting. I fixed my items

stone sage
#

How should I go about doing this?

simple zodiac
#

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) => {...})

stone sage
simple zodiac
#

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

stone sage
stone sage
stone sage
simple zodiac
#

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

stone sage
#

would it be better to switch to using node for this to work

simple zodiac
#

you have to use both

#

look

#

our goal is to write a text into the servers console directly

stone sage
#

should i like setup what you said with node and trigger the function with my previous scripting?

simple zodiac
#

you have to send a http request to the node process

stone sage
viral plaza
#
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.

inland merlin
#

In case that's messing up the xyz

#

Almost seems like your tryn to access a different chunk some reason

viral plaza
#

I’m trying to generate the "islands" 100 x away and 100 z away every island

#

And it can’t be decimals

inland merlin
#

Maybe add a ticking area before generating those, and then remove the ticking area after

inland merlin
#

Oh lol didn't look there

#

One sec

#

Wish I was home on my pc to try this

viral plaza
#

I do everything on mobile sadjoe

inland merlin
#

Geez

viral plaza
#

This didn’t take too long but still a pain I had to download and fix the extensions for each icon

inland merlin
#

Wow very nice

viral plaza
#

Thanks

pliant bramble
#

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

pliant bramble
wary edge
pliant bramble
#

ah that sucks lol, thanks, I will have a look at that 👍

past blaze
#

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'.
wary edge
past blaze
#

Oh shoot, I forgot about that

wary edge
#

#1067535608660107284 message

past blaze
#

Thanks

shy leaf
#

which one is better in general, Date.now() or system.currentTick?

subtle cove
#

ms

#

curentTick is affected by game lag

shy leaf
#

gotcha

shy leaf
wanton ocean
#
 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.
valid ice
shy leaf
#

i cant think of any other way to pass damage value from entityHurt to entityHitEntity WHY

valid ice
#

Hmm

#

Why, may I ask?

cinder shadow
#

You can definitely store their health into a property and check for a change with an entityHitEntity event

shy leaf
valid ice
#

Still confuzzled

shy leaf
#

basically uh

#

i have an entityHitEntity event that fires a function
and the function gets damage from entityHurt

#

it needs millisecond precision but

shy leaf
valid ice
#

Why is it that precise?

shy leaf
#

im making weapon cooldown (and bypassing iframes)

#

but uh

#

yeah, its buggy because of how tick works

valid ice
#

I always just recommend setting health directly for bypassing iframes

shy leaf
#

i do that too but

#

its not just about bypassing iframes, the weps have special abilities too

shy leaf
#

😔

#

or maybe... i could use async

fallow rivet
#

Is there a link where I can learn AddItem?

buoyant canopy
random flint
#

entityHitEntity.subscribe()
let damage = 0;
entityHurt.subscribe() //get damage here
entityHurt.unsubscribe()

shy leaf
#

just wondering

random flint
#

idk.

shy leaf
#

one way to find out

random flint
#

actually, I think it would be better with async yeah

shy leaf
#

last time i tried async there was noticable delay between the events

#

for some reason

random flint
#

let damage = await hurtDamage();

async function hurtDamage() //promise that returns the damage from entityHurt if it fires. Otherwise 0

shy leaf
#

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

random flint
shy leaf
#

welp gonna use that

#

it works better than i thought

random flint
#

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

shy leaf
#

i always thought it was just because of event order

random flint
#

who knows. that was just my assumption. ^

fallow rivet
#

Does Additem work with TypeScript?

wary edge
fallow rivet
#

"entry": "scripts/main.ts",

#

I did this and it gives an error

granite badger
#

you have to compile TS files to JS

fallow rivet
#

Is there a video about this?

wary edge
remote oyster
fallow rivet
random flint
#

You know... you don't have to code in TypeScript just so you can make addons

remote oyster
# fallow rivet Do I need to download an app to compile?

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.

random flint
fallow rivet
#

I write code with my phone

fallow rivet
random flint
#

i use plain js

remote oyster
# fallow rivet 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.

remote oyster
fallow rivet
remote oyster
#

TS is only a superset of JS.

random flint
#

the method, or a custom function

fallow rivet
#

This is why I tried Ty

fallow rivet
random flint
#

addItem method from the Container class works with JS too

fallow rivet
#

Hmm ok

#

Is it possible for me to give an item with low durability with Additem?

random flint
#

For clarification, TypeScript is just modified JavaScript for development. It'll get compiled into plain efficient JS, so basically just JavaScript with extra steps

fallow rivet
#

I understand

random flint
fallow rivet
#

Thanks

#

Can I ask for one more thing?

#

I need to add enchant to this too

random flint
# fallow rivet I need to add enchant to this too

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

fallow rivet
#

Thanks

fallow rivet
subtle cove
#

addEnchantments([
{},
{},
{}
])

subtle cove
#

import that EnchantmentType

fallow rivet
#

Ok

celest fable
fallow rivet
#

Hm

celest fable
fallow rivet
umbral scarab
#

Does anyone know if its possible to disable trident riptide collisions?

cold grove
#

And triggering event in script

#

But, what are the conditions to assume that the player is flying with riptide? 🤔

acoustic basin
#

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

thorn flicker
#

I mean there's probably a way but... I dont see the point if features are functional

acoustic basin
#

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

acoustic basin
#

also, it generates under ground

thorn flicker
#

so you could just use a single block feature.

acoustic basin
#

orrrr, use a command block with /structure command

thorn flicker
acoustic basin
thorn flicker
#

and what is that solution?

acoustic basin
cold grove
#

Is that bettet than natural generation? Natural generation also replace blocks

acoustic basin
#

instead of making custom block/entity, i'll just make it with command block

cold grove
#

I mean world generation*

thorn flicker
#

with the command block itself?

#

lol

acoustic basin
#

ye

thorn flicker
#

cool

acoustic basin
#

wait, i'll show u in dm

#

i'll make it rq

thorn flicker
#

I have an idea on how it will be

thorn flicker
fiery solar
#

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?

cold grove
#

Chunks need to be loaded too

#

It throws an error if you try to place a structure ouside the world boundaries

fiery solar
distant tulip
#

maybe we can fill unloaded chunk with that

solar dagger
#

Looks like nobody read this before?

prisma shard
#

Is it possible to make a custom event with subscribe and unsubscribe methods?

prisma shard
prisma shard
prisma shard
#

and i dont know how to make it have subscribe and unsubscribe methods

still rampart
prisma shard
prisma shard
#

i want to see how you do it your way

glacial widget
#

anyone got the new npm for the update?

prisma shard
prisma shard
grave thistle
#

Is the most current (stable) version of server API 1.11.0 and server ui API 1.1.0?

remote oyster
#

Update came out earlier.

grave thistle
#

Ah, thanks for letting me know

remote oyster
#

No problem

viral plaza
#

Can anyone tell me what’s new

sudden nest
#

Stable scripting addons go brrr

#

Is Minecraft debugger diagnostics working now in latest stable?

remote oyster
fallow rivet
#
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?

flat dove
#

Anyone here able to help me with my post?

#

new update has broken some things Im not quite sure on how I fix it

remote oyster
#

You can print it to console.

glacial widget
#

how do i fix items?

solar dagger
#

Anybody know how to get the dynamic property of an entity that died? Seems like there's no before world event for entity die...

fallow rivet
solar dagger
remote oyster
solar dagger
#

I know that...

#

Im going for a different approach either way. So thanks for the 'help'

remote oyster
#

If loaded, it should have no issues reading the dynamic property. Could you explain in more detail or share some code?

wary edge
#

It would make sense though since the entiy not longer exists it frees up the proeprty

remote oyster
#

Which means the entity is not loaded.

wary edge
remote oyster
remote oyster
wary edge
fallow rivet
remote oyster
solar dagger
#

Y'all are making it a bigger deal than it is, I was only asking for a different approach

#

🤦

distant tulip
#

what the point of tameable component if it get removed when the entity is tamed?

wary edge
distant tulip
wary edge
distant tulip
#

is this a bug?

wary edge
#

Works as intended since once its tamed you dont need that component anymore

distant tulip
serene radish
#

what would be the best way to kick a player out of a server form?

serene radish
#

i should've clarified i wanted stable

valid ice
#

welp

serene radish
#

welp

solar dagger
#

You could just crash their game 😈

fast lark
#

Welp

weary umbra
#

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")
        }
    })
})
still torrent
#

what is alpha?

wary edge
still torrent
wary edge
#

Yep

still torrent
#

😦

buoyant canopy
#

what's the latest version of the stable api?

buoyant canopy
#

thanks

scarlet hemlock
#

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

honest spear
distant tulip
#

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/

scarlet hemlock
#

I found Jayly's website, which I think is clearer than the official documentation

scarlet hemlock
#

It may be there somewhere, but it isn't easy to find (at least not for me)

distant tulip
alpine ibex
#
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?

scarlet hemlock
distant tulip
scarlet hemlock
#

I may be looking at the wrong place...

scarlet hemlock
distant tulip
shy leaf
#

its usually there

scarlet hemlock
distant tulip
shy leaf
#

what are the stuff that moved from preview to beta?

scarlet hemlock
#

So Jayly's should be the one to go to

distant tulip
shy leaf
#

from preview to beta in stable

true isle
#

Read the changelog lol

shy leaf
distant tulip
shy leaf
#

just wanted to know specific stuff

#

but ehhhh fine ill check it

true isle
#

Lol

#

Lazy

shy leaf
#

😔

distant tulip
#

@shy leaf
potions api thing
removed old items from MinecraftItemTypes
added some other enums types
and a lot of stuff moved to stable

shy leaf
#

POTIONS

#

YESSSSSSSS

distant tulip
#

yep
and the ui lib 1.2.0 is stable now

shy leaf
distant tulip
#

sumonable wind charge

shy leaf
#

i love this update

distant tulip
#

and the camera orbit thing is no in the api

shy leaf
distant tulip
#

alr have fun

dawn zealot
#

how do i convert this to scripts

valid ice
#

run_commands in entities can be moved to queue_command

#

works the same

dawn zealot
#

so the events still work?

valid ice
#

yes

dawn zealot
#

YESSSSSSS

valid ice
#

entities are not changed, besides run_command being remade into queue_command

dawn zealot
#

so liek this

#

like

valid ice
#

ye

dawn zealot
#

omfg i thought i was bouta go thru a midlife crisis

#

ive already had 1 of those today

valid ice
#

but I mean you could probably move whatever is activating those events to scripts anyways

dawn zealot
hardy rain
#

didnt they remove it?

valid ice
#

no?

hardy rain
#

it doesnt work for me

#

but it did before the update

sudden nest
#

It exists in the documentation, but not in the WorldAfterEvents

#

Weird

valid ice
#

It's still a beta APIs thing

sudden nest
#

Oh

hardy rain
buoyant canopy
#

getBlockFromViewDirection, gets the block from the view direction... not what block the player is aiming at.

distant tulip
sudden nest
#

What does this Unknown block during Deferred BlockDescriptir resolution error means?

buoyant canopy
inland merlin
#

Welp

buoyant canopy
#

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

inland merlin
#

Yeah, hmm

buoyant canopy
#

so playerInteractWithBlock is still needed after all

inland merlin
#

Well, maybe that's on purpose? Use blockintwrqct at that point?

#

Oh lol you said it

#

View vs actual interaction

distant tulip
#

nvm that won't get the exact face

#

hmm

#

itemUseOn is the only option i think

valid ice
#

if only getBlockFromCursorDirection() Why

distant tulip
buoyant canopy
distant tulip
#

yeah

buoyant canopy
#

well, i guess i will sacrifice the mobile players bao_doggo_blank

valid ice
#

I hate mobile too, dw

#

Separate UI angry
Bad cursor (see above) angry
Item use & block mine are same button angry

distant tulip
#

no swing on air

buoyant canopy
#

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)

distant tulip
#

cooldown

valid ice
#

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

buoyant canopy
distant tulip
#

probably not
didn't run into that problem tbh

buoyant canopy
#

i mean for mobile players, if they start using the item they will also hit the block

wary edge
#

Force them to use split controls schema

buoyant canopy
distant tulip
#

more like tell them to change it

wary edge
#

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

buoyant canopy
#
  • I won't use split controls myself, it's horrible
wary edge
#

I love split controls, love the crosshoair

buoyant canopy
#

the cross hair is fine but the forced joystick instead of movement buttons is way too dangerous

viscid horizon
#

all my scripts are broken hip hip hooray

random flint
cold sage
#

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']

cinder shadow
#

It could not find the export BlockVolume in Minecraft/server

random flint
#

BlockVolume don't exist

#

in ur Minecraft/script version

fleet pewter
cold sage
random flint
random flint
#

understanding the error helps debug your codes

dawn zealot
#

how would i convert this command using the removal of hcf stuff because i dont understand the docs at all

pale terrace
#

what is waitTicks for and whats the difference with runTimeOut

random flint
dawn zealot
granite badger
dawn zealot
cold sage
amber granite
#

From
"modern JavaScript" website

drifting ravenBOT
#
Learn JavaScript

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

shy leaf
#

how do i use Difficulty enum?

granite badger
amber granite
#

Import it from server module

#

And
GameModes.survival

#

Or idk

shy leaf
#

uh like

amber granite
#

They are just the survival type id

shy leaf
#

for checking (if difficulty) or whatever that

amber granite
#

On objects

shy leaf
#

also difficulty

#

not gamemode

random flint
#

Difficulty lol not Gamemode

amber granite
amber granite
#

I mean to detect teh difficulty

#

The only thing u can detect

#

If world is on hardCore mode

#

Or not

amber granite
#

@shy leaf

#

U use them the same way

#

Difficulty.hard
Or
Difficulty.Hard

  • one of them
    easy
    etc...
#

U import it

#

From server too

random flint
amber granite
#

import { Difficulty} from "@minecraft/server"

random flint
amber granite
#

Yes ,

random flint
#

ok

amber granite
#

My brain is on saving mode so

#

: P

#

I need to sleep anyways

valid ice
rich kernel
#

I get this error but “minecraft:tick” component doesn’t seem to exist
or is it beta?

#

nvm im stupid

somber echo
#

It is possible to obtain water or lava with getTopmostBlock?

glacial widget
#

do u love mc

fallow rivet
#
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?

fallow rivet
#

What

shy leaf
#

content logs?

#

the thing you turn on

#

for error logs

shy leaf
glacial widget
#

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?

glacial widget
fallow rivet
shy leaf
shy leaf
#

whoopsie

glacial widget
#

well the member one

shy leaf
#

whatcha trying though

glacial widget
#

if i add && then i would need both

glacial widget
#

very simple so idk why i am having problems

shy leaf
#
if (!(player.hasTag("verify") || player.hasTag("member"))```
glacial widget
#

i thought you would need to add the ! on both statments

shy leaf
#

well youre using ||

glacial widget
shy leaf
#

you want it to check if the player doesnt have any of those tags, right?

shy leaf
#

|| returns true if any check inside is passed, and ! reverses that

shy leaf
#

if the player has any of those, it returns false

glacial widget
#

i understand now

#

thanks for breaking it down for me

shy leaf
#

cheers

remote oyster
#

Returns true if they don't have verify or if they have member. The second condition isn't negated with !

remote oyster
#

Doesn't matter

#

Oh wait

shy leaf
#

What

remote oyster
#

My bad

#

I didn't see it lol

shy leaf
#

understandable

remote oyster
#

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")) {

};
shy leaf
#

thats better

remote oyster
#

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).

remote oyster
# fallow rivet Help pls

What exactly are you trying to accomplish? Your code looks fine. Could be an issue related to the function you are calling.

fallow rivet
remote oyster
#

Why are you subtracting 1 from result.selection

#

Remove it.

fallow rivet
remote oyster
#

1 or 0 I presume so let's assume it's 1. You are targeting 0 because you are checking for (1 - 1).

fallow rivet
#

Yea

remote oyster
#

But 0 isn't what you selected. You selected 1 in that example so why would you check 0.

#

Does that make sense?

fallow rivet
#

for (let i = 0; i < inventory.size; i++) {
Here i is the slot of the player's item

remote oyster
#

I'm talking about the line where you print console.warn().

Remove -1 from result.selection and see what it does.

fallow rivet
#
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)
}
});
}
remote oyster
# fallow rivet ```js function createauction(player) { const inventory = player.getComponent("mi...
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.

glacial widget
#

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 =>{
    })
}
distant tulip
#

what error

glacial widget
#

nvm i did the .dropdown wrong

fallow rivet
glacial widget
#

but i fixed it

fallow rivet
#

Ok

#

1 sec

glacial widget
#

i fixed it

fallow rivet
#
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

glacial widget
glacial widget
fallow rivet
#

Then all you have to do is this

#
.dropdown("Players", playerNames);
shy leaf
#

are blocks typeid and item typeid usually the same?

fallow rivet
shy leaf
#

not the namespace

#

like cobblestone item and cobblestone block

#

those are same

#

but im not sure about other things

fallow rivet
shy leaf
#

hmmmm

fallow rivet
#

@shy leaf

shy leaf
#

hello

fallow rivet
#

Minecraft:daylight_dedector
Daylight sensor

shy leaf
#

might as well just use getItemStack

glacial widget
glacial widget
shy leaf
#

thats Spy

cold grove
shy leaf
#

from TF2

cold grove
#

Array.from copies the array, you will use it in very specific cases

#

But this is not one

shy leaf
#

cant you just do

world.getAllPlayers().forEach(p => {
    //code
});```
#

oh wait

#

player names

#

🗿 nvm

cold grove
#

Is the same anyways

chrome flint
#

hey, does everthing moved to stable?

granite badger
slow walrus
shy leaf
#

there we go

chilly moth
#

@rigid torrent

rigid torrent
#

That’s me

chilly moth
#

the template of log doest work properly

#

it doest allow log to be placed on each other

rigid torrent
#

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

chilly moth
#

ok

#

do you have a sapling template

rigid torrent
#

You can, however, fix it yourself by cancelling the interaction and place the block instead

rigid torrent
chilly moth
#

hm

chilly moth
#

also "tag:wood": {},
how does it work

rigid torrent
chilly moth
#

no error in log

rigid torrent
rigid torrent
chilly moth
#

do I need component for chopping speed etc

#

for custom blocks

rigid torrent
#

I don’t quite understand

chilly moth
#

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

rigid torrent
#

You can change mining speed at your own liking

rigid torrent
amber granite
#

@glacial widget

#

Change it to :

if ( ! ( X || Y ) ) {
}
glacial widget
amber granite
#

UW

amber granite
fallow rivet
#

Is there a 2.0 alpha for the Minecraft-server-form module?

wary edge
fast lark
#

Realms dont work 😦

drifting cobalt
#

how to detect if the villager is baby?

remote oyster
#

BDS works though lol.

amber granite
fast lark
#

can i ask a silly question about js?

oak lynx
#

I must be blind cuz i can't find custom entity components docs

granite badger
#

there isn’t such thing

oak lynx
#

So is there any way to run scripts when an event triggers for an entity

oak lynx
#

I thought they did something to datadriven stuff or was that just blocks and items (or maybe i just misremember stuff)

fallow rivet
#
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?

fallow rivet
fallow rivet
spare fox
remote oyster
#

👀

grave thistle
#

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.).

hardy tusk
# scarlet hemlock Guys, quick question. I'm new to Mc scripting, and I'm looking for a resource wh...

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 🙂

distant tulip
#

hes questions has been answered already

grave thistle
#

Also, what's the difference between a property and a dynamic property?

hardy tusk
distant tulip
random flint
hardy tusk
#

And the responses he got whree the first thing imo

distant tulip
#

🤨

hardy tusk
#

Thats a metaphor

amber granite
hardy tusk
amber granite
#

He means
entity.getProprety()

#

Na d
entity.getDynamicProprety()

sudden nest
#

Is entity property defined in entity still not removed?

amber granite
#

XD , bro was gonna explain oop for him

sudden nest
#

Like from the bee? Or wait imma read what entity perms first, me is confused

distant tulip
# grave thistle Also, what's the difference between a property and a dynamic property?

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

random flint
# grave thistle Also, what's the difference between a property and a dynamic property?
  • 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.

spare fox
hardy tusk
#

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

grave thistle
#

Thanks for all the replies. I've used dynamic properties a lot, just never normal properties

valid ice
#

They're useful for communication between the resource pack & the server yessir

random flint
#

Can the same DynamicProperty be accessed from a different pack? Or it's exclusively unique for each pack?

amber granite
#

No

#

It s on the pack uuid

#

Saved on it

distant tulip
sudden nest
#

Can't wait other peps showcase their projects or addons using scripts and stuffs with scripting api being stablebao_event_mobvote_crab

devout dune
#

Helllooo, are the block components. on_placed, on_player_place etc, deprecated, are they entirely replaced with cusotm components?

frozen vine
#

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.

frozen vine
gaunt salmonBOT
#

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]
wary edge
#

@granite badger any chance you can just make this a drop down or smthng. It is quiet big

hoary coral
frozen vine
hoary coral
#

I think you have something like

if(item...) {
  // code
}

just do it

// code
next sedge
#

ended up being in one of my scripts was literally just "vector" (fyi im not an idiot, it did not show in the search 😭 )

forest loom
#

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?

remote oyster
forest loom
remote oyster
forest loom
#

👍

fallow rivet
#

Is it possible to use Additem for a slot?

gaunt salmonBOT
#

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]
devout dune
#

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?

open urchin
#
block.setPermutation(
  block.permutation.withState("state:name", value)
)```
devout dune
open urchin
#

block.permutation.getState("state:name")

buoyant canopy
#

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

keen gull
#

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

distant tulip
devout dune
#

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 😄

grave nebula
#

why is bro pinging randoms

devout dune
distant tulip
#

also off-topic

wary edge
#

Is this from the precise rotation?

grave nebula
devout dune
devout dune
wary edge
#

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

willow gazelle
#

There is no tool to directly translate from Holiday features to scripting?

buoyant canopy
distant tulip
#

@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)

distant tulip
buoyant canopy
distant tulip
#

with commands

#

replaceitem

buoyant canopy
#

yeah, so setEquipment doesn't work as well

distant tulip
#

i think?

buoyant canopy
#

one second

distant tulip
#

alr

buoyant canopy
#

i guess i will resort to a scriptevent then

distant tulip
#

yeah

#

both detecting an item and replacing it can be done with commands

buoyant canopy
buoyant canopy
distant tulip
#

that doesn't kill the armor stand?

distant tulip
buoyant canopy
buoyant canopy
distant tulip
buoyant canopy
#

fantastic

devout dune
distant tulip
median stream
#

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.

buoyant canopy
distant tulip
#

tameable component get removed on tame

drifting pollenBOT
ebon niche
#

What version is block.getRedstonePower in now? I'm trying 1.14.0-beta and I'm getting a "not a function" error

ebon niche
#

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

wary edge
#

Inventory works but that doesnt include equopment

#

tater it really isnt in this case

pale terrace
#

When teleporting an entity using teleport, is it possible to disable the smoothing on the entity's position when changing position?

dense skiff
#

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?

valid ice
#

They are per-pack, yes. You could use scoreboards, I guess.

dense skiff
#

Hmm

valid ice
#

You could try doing something like player.__testValue = true and reading that in the other pack?

dense skiff
#

Like extending the player class?

valid ice
#

I guess, yes.

dense skiff
#

That's an interesting thought

valid ice
dense skiff
#

Do you have an example?

valid ice
#
if ((player.__tempCooldown ?? 0) > Date.now())  return;
player.__tempCooldown = Date.now() + 500; //Half a second of delay
dense skiff
#

Thanks. Will give it a shot when I decide make this change to my project

valid ice
#

Mind you, idk if it can pass data between packs, but it's worth a shot

dense skiff
#

Yep

rich kernel
fallen hearth
#

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`)
      }
  });
});
cinder shadow
#

How is it reaching 600 ticks

#

Any errors?

fallen hearth
cinder shadow
# fallen hearth

Check your runCommand, its different from the other one you specified

hoary coral
fallen hearth
hoary coral
#

use ```
${ev.block.location.x} ${ev.block.location.y} ${ev.block.location.z}

instead of `~~~`
valid ice
#

can also do ev.block.setType('minecraft:bone_block')

granite badger
fallen hearth
#

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?

tiny tartan
#

@granite badger

gaunt salmonBOT
#

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]
tiny tartan
#

its working fine now idk what was the problem

sudden nest
#

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.

valid ice
#

Purpose was java parity, iirc. They have separate blocks for anvil states (who knows why)

thorn flicker
#

thats my guess

valid ice
#

I'll take your word for that one lol

sudden nest
# sudden nest

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. 🤷‍♂️

grave nebula
#

is it possible to set bossbars to each individual player

#

ex: player names for each player

unique dragon
#

#1067869374410657962

shy leaf
#

they changed the anvils to have different ids

#

for broken anvils

sudden nest
#

anyone have a stable-version of isOp(), i can use?

dense skiff
valid ice
#

I have never tried that on world before, just on entity/plauer

dense skiff
#

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?

distant tulip
#

use tags or scoreboard database

granite badger
#

Does that mean the world objects are different for each pack?
definitely, each pack has its own environment

distant tulip
#

must be
that can break a lot of stuff

dense skiff
#

need some good IPC (inter-PACK communication hahah) here lol

#

Ik tags and scoreboards

granite badger
#

scriptevent

dense skiff
#

true

#

that's a good one actually

dense skiff
valid ice
#

Ah, good to know 👍

fallow rivet
#
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

sudden nest
# fallow rivet ```js const enchantments = selectedItem.getComponent("enchantable").getEnchantme...

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

fallow rivet
slow walrus
#

removing the variables won't change anything

#

they're passed by reference

slow walrus
#

yep

sudden nest
#

oh xp, my bad

fallow rivet
distant gulch
#

addEnchantments wants a Enchantment[] input not a string[]

gaunt salmonBOT
#

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 0 errors.

Lint Result

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

distant gulch
#

the object:

Enchantment = {
  level: number,
  type: EnchantmenType: {
    id: string,
    maxLevel: number
  }
}
distant gulch
fallow rivet
slow walrus
#

it's pretty basic js

distant gulch
# fallow rivet 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

slow walrus
#

remove all those unused params lmao

distant gulch
#

true, but i dont know if he needs them or not

slow walrus
#

eh ig

distant gulch
#

maybe in future he'll need them

distant gulch
distant gulch
#

the error message would be better for understanding

fallow rivet
distant gulch
#

uhhhhh

fallow rivet
#

I've been dealing with this since yesterday and I'm about to go crazy.

distant gulch
#

maybe a better code structure would make it easier ro fix

granite badger
#

can my bot help

fallow rivet
#

Maybe

distant gulch
#

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

gaunt salmonBOT
#

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 4 errors:

main.js:138:5 - error TS2365: Operator '>' cannot be applied to types 'string | number | boolean' and 'number'.

138 if (price > 0) {
        ~~~~~~~~~

``````ansi
main.js:197:40 - error TS2345: Argument of type 'string | number | boolean | Vector3' is not assignable to parameter of type 'string'.
  Type 'number' is not assignable to type 'string'.

197 if(data != undefined) {st = JSON.parse(data);}
                                           ~~~~

``````ansi
main.js:214:39 - error TS2365: Operator '+' cannot be applied to types 'string | number | boolean | Vector3' and 'number'.

214 world.setDynamicProperty("auctionid", auctionid+1);
                                          ~~~~~~~~~~~

``````ansi
main.js:219:31 - error TS2345: Argument of type 'string | number | boolean | Vector3' is not assignable to parameter of type 'string'.

219         const st = JSON.parse(stJson);
                                  ~~~~~~

Lint Result

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

sudden nest
#

I'll try it later, if this is not fixed yet if I can help

dense skiff
woven loom
#

anyonone got a action ui that to show inventory

hazy nebula
#

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?

granite badger
hushed ravine
#

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

sudden nest
distant tulip
#

what version did fix the ModalFormData scroll bar starting from the bottom?

celest fable
distant tulip
celest fable
distant tulip
celest fable
#

maybe you actually can, just need to make the thing inside the form less

chilly moth
#

@prisma shard do you have template for sapling

chilly moth
#

@distant tulip not Hcf I want Scipt

lone thistle
#

Oh wait, you did

crude bridge
#

#1273656649705586688

crude bridge
tawny reef
#

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) {
prisma shard
shy leaf
#

@valid ice how do i use createPotion for itemStack

devout dune
#

Does anyone know why my custom component is not registering?

valid ice
cinder shadow
devout dune
#

they are replacing block "events" and generic built in components like "on_player_placed"

cinder shadow
#

yeah but

random flint
#

I like how beforeEvent playerPlaceBlock is beta, while the custom component for block: beforePlayerPlaceOn is stable.

devout dune
#

anyone know why mine is not registering? did i set it up wrong

deep plank
amber granite
#

@distant tulip

devout dune
#

My log did not seem to fire at all. So worldInitialize is doing nothing rn? do i need to be in a different version..

shy leaf
#

the id for effects arent working

#

i think its different for createPotion

granite badger
#

they don’t use ids, again check examples (they’re hidden)

random flint
devout dune
shy leaf
#

Oh bruh

#

you have to import it

random flint
#

beforeEvent worldInitialize needs to be called before the world loads. So subscribing in afterEvents scopes isn't an option

valid ice
fallow rivet
devout dune
random flint
devout dune
shy leaf
#

where tf is the full list of potion effect types

#

what is wrong with mojang

#

jeez

random flint
devout dune
amber granite
#

☠️

#

There is no main in js

random flint
devout dune
amber granite
#

The main function

#

Of other programing languages

#

Isn't available

#

In js

#

U just write ur code

devout dune
#

im confused, its a custom name

amber granite
#

Oh ☠️

devout dune
amber granite
#

I thought u are java or cpp developer who wants to write script api ☠️

random flint
#

Other programming languages usually have this function called main that would be called for the first time ig

devout dune
devout dune
#

If not, I can try to refactor to not use system.run! Just not 100% confident with it yet

random flint
#

Yes, you can still use system.run to exit the beforeEvent/read-only scope. Just specifically, don't use it to delay worldInitialize beforeEvent.

devout dune
#

but this is obviously delaying it?

random flint
#

Yes, that's delaying the worldInitialize

#

though, you can add the other event listener inside the system.run

devout dune
#

and this constructor is called during the first system.run call. here:

random flint
devout dune
#

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 });
      });
    });```
random flint
#

I'll say it clearly, put world.beforeEvents.worldInitialize outside any system.run()

devout dune
random flint
devout dune
random flint
#

Technically, your code would still work even without the system.run

devout dune
random flint
#

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.

devout dune
random flint
#

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.

runic crypt
#

hey guys
how do i make a money transfer script ?

cold grove
viral plaza
#

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);
    });
}
cold grove
honest spear
#

yes, basicly when something is not defined it means its not defined

remote oyster
distant tulip
#

average script developer

hardy tusk
dense skiff
#

just got my first one of those 😂

honest spear
honest spear
#

10 Years or more?

merry ibex
#

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"
}
]
}

distant tulip
#

log?

merry ibex
#

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");

distant tulip
#

it is dependencies not dependences

merry ibex
#

thx{