#Script API General

1 messages Β· Page 26 of 1

subtle cove
#
if (item9?.typeId === "minecraft:stick") {
  item9.nameTag = "f"
  inv.setItem(9, item9)
}```
untold magnet
#

getItem(9).amount -= 1 isn't working
i tried inv.getSlot(9).amount -= 1 and it works
should i do it like this inv.getSlot(9).nameTag = 'f'?

subtle cove
#
const item9 = inv.getSlot(9)
if (item9.hasItem() && item9.typeId === "minecraft:stick") item9.nameTag = "f"
untold magnet
#

it works with getSlot

#

alright, i can work now

sage portal
#

does the BlockComponentStepOnEvent work for non-collision blocks that you walk through? I not, how can you detect if a players walks through a non-collision block?

subtle cove
buoyant canopy
#

if i move the structures into a subfolder of the structures folder, do i need to change something in the structure manager code?

subtle cove
#

filename is allu need

buoyant canopy
#

great

supple yoke
#

bruh

#

just deleted a week worth of work

#

fml

#

the built product is still here

#

that's good

#

should have made a GitHub repo

#

it took the git folder with it 😭

#

fuck you neotree

#

welp take it as a opportunity to refactor

lyric kestrel
#

What were you working on?

digital swallow
#

How do I give a wolf armor through scripts? Wolves seem to not have an Equippable component, so I can't use setEquipment like I can with players?

#

Like, if I get the "equippable" component of a wolf, it's just undefined

#

Wolves do equip armor to a "slot.armor.chest" though, so this is very bizzare

#

Ok, so you can just tag the wolf when you spawn it with scripts, and then give the wolf armor based on the tag with the replaceitem command, but it feels wrong lol

distant tulip
digital swallow
distant tulip
#

alr

solar dagger
#

Im trying to make a leveling system for a tame, i wanted to know what would be the best way to get kill xp with .applyDamage()? Basically the player will ride this tame and level it up by doing certain tasks, killing a mob is one of them.

autumn kraken
#

Hey guys. Just wanted to let you know that today is my last day at Mojang. It was a blast engaging with this community and working together to build the new scripting system and APIs. Can't wait to see all the awesome things you make in the future. minecraftheart

granite badger
#

Thank you memcpy!

sharp elbow
#

I wish you good luck with whatever you pursue next!

honest spear
#

Thank you memcpy!

simple zodiac
empty yoke
#

How do I detect if an entity is moving forward or backward, without using Velocity?

buoyant canopy
empty yoke
buoyant canopy
#

btw which entity other than the player can walk backwards?

empty yoke
#

rideable entity

#

if I press w the condition always occurs because applyKnockback always increases the velocity, but if I do clear it does not work applyKnockback always there is no method only through tp, but through tp there is a problem A and D does not work only through mouse movement you can move with the vehicle

sharp elbow
#

Try comparing motion across ticks. You already know which direction the scooter moved in on the last tick, as well as the impulse you applied to it (theoretically), so you can subtract that vector from the movement direction in the current tick.

#

That will not be easy though

hardy tusk
untold magnet
#

for (let i = 1; i <= 4; i++) { ,,, } this should detect numbers from 1 to 4?

lyric kestrel
#

Is Herobrine's Chest UI just for shops?

distant tulip
lyric kestrel
#

I'm a bit confused with it

distant tulip
obsidian coyote
abstract cave
#

is there a way to control mob spawn rates using script or control the spawn rates within a certain area

untold magnet
#

jeez

#

i found the problem in my system

#

it was this: entity.setDynamicProperty('sk', sk + 1)

#

the sk + 1 is broken and super slow

pale terrace
#

whats the difference between system.runTimeOut and system.waitTicks?

deep quiver
oblique heath
#

how long has the getBlocks function from the Dimension class been in beta?

honest spear
#

its kinda new method

round bone
#

can I somehow connect to WebSocket on Realm?

untold magnet
#

ey, i need a little help

#

how can i use inv.setItem(5, ???) to increase the item in that slot?

subtle cove
#

.amount++

untold magnet
subtle cove
#
if (!slot5) inv.setItem(5, new ItemStack('minecraft:stick', 1));
if (slot5) {
    slot5.amount++;
    inv.setItem(5, slot5)
}
untold magnet
subtle cove
#

yeah

#

itll error if theres no item tho

untold magnet
#

i can deal with them

#

for now

#

I'll take some informations about those alloys

untold magnet
#

hmm

#
  if (!output) inv.setItem(5, new ItemStack(itemType));
  if (output.amount < 32 && output.amount > 1) inv.getSlot(5).amount++;```those have a log
#

output = inv.getItem(5);

untold magnet
#

if (!output?.hasItem) console.warn('empty')
const output = inv.getSlot(5);
||const @subtle cove = help(t17x);||

#

i just want to detect if that slot is empty

subtle cove
#

thats where u use isValid()

ivory lagoon
#

I wish you could force the player to interact with an entity

crude flame
#

Hi, how can i fix the code, the console says: native function does not have the required privilege

#

world.beforeEvents.itemUse.subscribe(ev =>{
ev.source.sendMessage("HII")
ev.source.dimension.createExplosion({x:-40,y:1,z:3}, 10);
})

untold magnet
ivory lagoon
crude flame
#

how do i use system.run?

ivory lagoon
crude flame
#

nothing happens

ivory lagoon
crude flame
#

yes

#

HI gets send but no explosion

untold magnet
#

@subtle cove same log

untold magnet
untold magnet
#

const { x, y, z } = player.location;
//({ x: x, y: y + 5, z: z}) will generate an explosion above the player by 5 blocks

crude flame
#

thank you

#

do you know any great tutorials to learn bedrock coding?

subtle cove
#

just any javascript tutorial

round bone
#

or you can read these

quick shoal
#

anyone who know the error about of not a contain main file

#

idk how to fix it

#

PLZ help

distant tulip
quick shoal
sage sparrow
#

hi there! how can get the item type id from the entity item?

thorn flicker
sage sparrow
#

like this? javascript const entityItem = player.dimension.getEntities({ type: "minecraft:item", location: player.location, maxDistance: 10 }) const item = entityItem.getComponent(EntityComponentTypes.Item);

#

yep, that works, thx!

remote oyster
#

Since it's possible that you may not get any items returned.

#

entityItem will return an array as well. So if you have more than one object (item) then you will need to loop through entityItem, and then access its component.

round bone
#

can I somehow connect to WebSocket on Realm?

crude flame
#

is there a way to get the inputs by the player, like if the player presses the jump key?

round bone
crude flame
#

ok, thanks

deft nest
#

How can I add lore to items on the ground?

round bone
#

EntityItemComponent

#

yeah

oblique heath
round bone
#

health is 2 decimal

deft nest
round bone
#

not sure tbh

distant tulip
oblique heath
#

that sucks

distant tulip
#

fr

oblique heath
#

is there anyway to detect player input?

remote oyster
#

Assuming this behavior:

#1290336475803680809 message

oblique heath
#

movement input

remote oyster
ruby haven
#

Can someone help on what to import inorder to get the onplayerinteract_block function in Minecraft

distant gulch
#

WHERE IS RELOAD

#

the reload command is just nonexistent

elder heath
#

Good evening, a question, how do I get the enchantments of an item and show them in the console?

lone thistle
distant gulch
lone thistle
distant gulch
ruby haven
#

Is possible to make my own custom crafting table through scripts combining UI server module and Minecraft server module.

The idea is I will register a custom component with onPlayerinteract on it then it loads the UI however I don't have any idea what happens next

cold grove
#

there is already a custom crafting table block component

ruby haven
#

Are there any alternatives I don't want the custom crafting table component because it has this auto craft system I want to remove that

cold grove
#

no

ruby haven
#

I really makes my addon so easy to beat if I use that

cold grove
#

trades(?

distant gulch
#

HUH

valid ice
#

Remove admin commands from yourself in the pause menu crown and readd it

#

happens when you download a world from a realm

distant gulch
oblique heath
#

applyImpulse just adds to the current entity velocity correct?

unique dragon
#

uh

fiery solar
pliant kite
#

how to know which id item has?
For example
netherite sword id = 632

warm drum
#

im switching from minecraft:food to item custom component but the animation using q.is_using_item doesn't work

#

Anyone know how to fix it

crude bridge
#

#1290968640597790760

nocturne berry
#

How do you get the entity to be summoned with a tag?

      system.run(() => {
        block.dimension.spawnEntity('occultismus_arcanus:funace_entity',block.center());```
burnt lance
nocturne berry
subtle cove
#

entity.nameTag = "nametag"

nocturne berry
last latch
#

can someone explain to me how faceLocation works?

#

It shows always 0, 1, 0 or 0, 0, 0 as Vec3 (with decimals)

#

even tho i interacted elsewhere

distant tulip
#

you can add the block location to it to get world related location

last latch
wheat condor
#

do y'all think its useful to create a class that uses timers without using ingame ticks like you can set the timeout at 1ms?

fiery solar
#

Also, has anyone already done the work to get the biome at a particular block location? I could have sworn I saw something a few months ago but I don't see it in search.

last latch
wheat condor
distant tulip
#

@fiery solar


import { BiomeTypes, Player, world, system } from "@minecraft/server";

Player.prototype.findClosestBiomeAsync = async function () {
    const biomes = BiomeTypes.getAll();
    let closestBiome = null;
    let closestDistance = Infinity;
    
    for (const biome of biomes) {
        const loc = this.dimension.findClosestBiome(this.location, biome.id);
        if (loc) {
            const distance = vector3distance(this.location, loc);
            if (distance < closestDistance) {
                closestDistance = distance;
                closestBiome = biome;
            }
        }
        await new Promise(resolve => system.runTimeout(resolve, 0));
    }
    return closestBiome;
};


function vector3distance(a, b) {
    return Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z)
}
//example
world.getPlayers().forEach(player => {
    player.findClosestBiomeAsync().then(biome => {
        console.warn(JSON.stringify(biome));
    })
})
fiery solar
distant tulip
#

or are you planing to use filter

fiery solar
fiery solar
#

Wow, this is way faster than I thought it would be. Got the exact biome of every block in 25 chunks in 3.5 seconds.

distant tulip
fiery solar
distant tulip
nocturne berry
#

Does anyone know why the scripts are not working on the Aternos server?

mystic mortar
#

Alright. Waiting for new beta to drop. Im gonna try to see if I can implement my "creaking husk" idea.

#

Should be easy, as long as I keep it to listening to entity spawn and die events.

crisp surge
#

is it still possible to grab a double chest and do something like this:

const block = player.dimension.getBlock(tempBlock);
const container = block.getComponent(`inventory`).container;
const item = container.getItem(53);

if so how because i keep getting an error saying that slot provided is invalid. and the max is 26

unique dragon
#

make a console
warn with the inv size

#

console.warn(container.size)

crisp surge
#

thats why im confused

unique dragon
#

strange yes

#

and I don't think the double chests uses 2 entities

crisp surge
#

me neither.

#

this used to work is the thing. and i dont believe they updated it.

frozen vine
#

is it possible to use playerInteractWithEntity on mobs that do not have the component minecraft:interact?

abstract cave
#

Is there a way to set a mobs agggresion to the player

#

or another entity

#

using script

frozen vine
abstract cave
frozen vine
#

oh yes, sorry I thought you were answering me

oblique heath
#

is there a way to check how much experience an experience orb will give you?

untold magnet
#

ugh

#

how can i make it work inside loaded chunks only?

#

this happens with entity?.isValid()

random flint
untold magnet
#

if it is too complicated, I'll just leave it works inside unloaded chunks

thin steeple
#

does anyone know how to figure out whats causing a slowdown

crude bridge
#

you mean cooldown

#

?

thin steeple
#

no no no

#

like the slowdown ms thing that appears in your log

crude bridge
#

oh

#

idk

last latch
fading sand
#

how do i run an event for an entity shooting an projectile?

untold magnet
#

const item = entity.getComponent('minecraft:item'); for getting item entity?

pliant kite
untold magnet
#

getting the item entity, those

#

not mainhand thing

pliant kite
#

Inventory for item ig

untold magnet
pliant kite
#

are you trying to get entity component?

untold magnet
pliant kite
#

why do you need that

untold magnet
#

just like
/kill @e[type=item]

untold magnet
untold magnet
#

i knew it

fading sand
#

how do i run an event for an entity shooting an projectile?

unreal cove
fading sand
#

before i used run command in the projectile lol

unreal cove
# fading sand no ,like run an event once the entity shot an projectile

No events exist for that, there's just on entity/block hit for projectiles, but ig you could use the entitySpawn event, and just check if the spawned entity has minecraft:projectile component to further confirm it's a projectile, that component also has owner property which can be used to check for it's source

fading sand
fading sand
#

O:

#

How again? I couldnt seem to find it in the wiki

#

Dont tell me its simply getOwner..

#

(Idk if that exists)

untold magnet
# unreal cove Yes

if (reIy.includes(floorItem?.typeId)) floorItem.entity.remove; aren't working for some reason?

#

theres 30 different item type i want to remove, so i putted them all inside of that reIy

fading sand
#
let projectileEntity1Component = projectileEntity1.getComponent('minecraft:projectile');

let ownerEntity = projectileEntity1Component.owner
untold magnet
unreal cove
unreal cove
fading sand
#

Nice

#

Thx

untold magnet
random flint
untold magnet
#

ah, i see

untold magnet
untold magnet
untold magnet
# unreal cove Can u show full code?
const reIy = ['someCorrectIds']
const floorItem = entity.getComponent('minecraft:item');
if (reIy.includes(floorItem?.itemStack.typeId)) floorItem.entity.remove();```thats all
#

wait

untold magnet
unreal cove
untold magnet
#

entity.remove,
floorItem.entity.remove will not work right?

#

my feeling tells me entity.remove will remove all entities not only those items

untold magnet
#

then why its not working for mebao_icon_entities

sharp elbow
#

entity is locally defined as the current iteration of .getEntities(), so it should only remove those that match the conditions

subtle cove
untold magnet
#

damn it...

subtle cove
#

console.warn(entity.getComponent('item')?.itemStack.typeId)

fading sand
#

why do ownerEntity.setPropery("soldier:ammo", soldierAmmo-1); cause an error?

subtle cove
# untold magnet

import { system, world, DimensionTypes } from "@minecraft/server";


const dims = DimensionTypes.getAll().map(d => world.getDimension(d.typeId))

system.runInterval(() => {
    for (const entityItem of dims.flatMap(d => d.getEntities({ type: "item" }))) {

        const reIy = ['minecraft:apple']
        const floorItem = entityItem.getComponent('minecraft:item');
        console.warn(floorItem.itemStack.typeId);
        if (reIy.includes(floorItem.itemStack.typeId)) entityItem.remove();
    }
}, 20);
fading sand
subtle cove
#

spelling

fading sand
subtle cove
#

setProperty

fading sand
#

oh sheet not again πŸ˜‚

#

thx

distant tulip
#

setVelocity()
clearVelocity()
setRotation()
is there is any reason why all those not present in the player class?
is there a bug that preventing them from being added or what?

sharp elbow
#

You could say that. Those would probably cause a client-server desync if used

#

The reason applyKnockback() works and applyImpulse() doesn't, I imagine, is that the former calls upon an existing code path in Minecraft (in this case, the knockback roar). Similarly for why teleport() works and setRotation() doesn'tβ€”the former, in essence, invokes the same logic as the /teleport command

#

So in theory, if Minecraft supports applying arbitrary velocity or rotation and can send those packets to the client, then scripting should support it too

#

I'd love setRotation() πŸ˜”

distant tulip
sharp elbow
#

Eh, not really. Only proper client-server communication

distant tulip
deep plank
#

I don't see setVelocity() in docs.

distant tulip
#

i guess camera command?

sharp elbow
#

Basically everything that works relies on communication in some form. The server tells the client what to do, and the client tells the server what its intentions are

distant tulip
sharp elbow
#

Camera is a good example. Server tells the client "you should move your camera to this location with this rotation"

distant tulip
#

yeah i see your point

fading sand
#

can someone send me entity event event signal code preset rq?

distant tulip
fading sand
#

DataDrivenEntityTriggerEventAfter

distant tulip
#

should look like
world.afterEvents.dataDrivenEntityTrigger.subscribe()

fading sand
#

Leme see

#

alr

#

now

#

how do i get the family names of an entity ?

frozen vine
#

is it possible to use item.nameTag and elr use the name chosen in the lang file?

fading sand
#

i want to get the teamxyz family name, like get team1 and make it so the result is 1 and if the entity has an family with the name team2 the result should be 2

frozen vine
distant tulip
fading sand
distant tulip
#

check the entity class
there probably a getFamilies() function
as for the second one just filter them out

fading sand
#

hm

thorn ocean
#

Does anyone know if system.runJob allows to return a value from a function?

untold magnet
#

i was writing the entity killer inside of the block entity

#

i mean if (entity.typeId === 'myBlock:entity') { /// item entity killer }

#

i put it outside that and it works fine now

#

actually

#

bec im too lazy

#

i will not make a system that will remove those items from the player or the entity inventory

#

well,

#

how can i make the script work only inside loaded chunks?
bec the block entity keeps working inside unloaded chunksbao_foxxo_blank

#

entity.isValid() will make it work inside unloaded chunks, how can i reverse it? like putting a ! or something?

thorn ocean
untold magnet
#

it should console.warn when it is inside the loaded chunks

#

it does not console.warn even inside the unloaded chunks

thorn ocean
untold magnet
thorn ocean
crisp surge
#

does anyone in here know term cmds for bds?

remote oyster
crisp surge
#

i just accidently pressed ctrl+z in a term while my bds was open and it stopped it and im lowkey scared i messed sum up

#

it also wont open again

untold magnet
#

wait, is it bec i have this:
entity?.isValid() && block?.isValid()?

remote oyster
crisp surge
#

it wont open the server again it says something about freeing up ports. and it says exiting program

untold magnet
remote oyster
crisp surge
#

im on windows but my friend is hosting it on a docker through linux

#

so linux

remote oyster
# crisp surge so linux

In the terminal enter the following:

ps aux | grep bedrock_server

This will, or should, show a list of process ID's related to the application for the server still running in the background. Technically you should only see one. It will have a PID which is short for Process ID. Grab that and enter the following in the terminal:

kill -9 12345

12345 would be the PID for your case so make sure you replace that. -9 basically tells the command to forcefully kill the Process.

crisp surge
#

okay thank you so very much

remote oyster
#

Welcome. After that you should be able to run the server again

crisp surge
#

do i kill 2?

remote oyster
#

Kill all three of them.

crisp surge
#

okay

#

it worked thanks so much!

remote oyster
#

Linux FTW πŸ₯³

thorn ocean
remote oyster
#

^

untold magnet
#

should i remove block?.isValid() from the script?

thorn ocean
untold magnet
thorn ocean
untold magnet
#

sorry but my brain isn't braining on the isValid section

#

can u explain to me specifically what they are for?
entity?.isValid() && block?.isValid() ← i have them like this

#

tell me what should i change

thorn ocean
#

entity?.isValid() && block?.isValid() == true

untold magnet
remote oyster
# untold magnet so `entity?.isValid{() === false` will make it work only inside loaded chunks?

It will not work inside loaded chunks just because you are checking for isValid. The purpose of that property is to tell you if the entity is loaded or not. If they are not loaded it will return false. If they are loaded it will return true. It does not matter how you try to manipulate the property. The results will be the same whether the entity is loaded (true) or not loaded (false).

untold magnet
#

i just want to make the script work only when the entity inside loaded chunks, like the spawn loaded chunks,

remote oyster
#

Actually, I'm ahead of myself. Player entities will be in loaded chunks. I believe other entities are programmatically designed to despawn or freeze when a player steps away or logs off. Now I'm curious on how far that extends outward with entities πŸ‘€

untold magnet
#

i see

#

so entity.isValid is quite useless right?

fiery solar
fiery solar
remote oyster
untold magnet
oblique heath
#

just check if the entity object itself exists

#

from the entity list

cerulean cliff
#

out of curiosity, how do I send a form using the scripting api and get the result of which button/input or what every has been used?

#

let's say I have a custom form

#

an input, maybe even a slider and a toggle

untold magnet
#

finally

#

after 5 days of coding a script,

#

oh, wait

#

i forgot

#

j gotta make the slot 5 lockedbao_foxxo_blank

#

i think

#

if (item5?.typeId !== 'minecraft:stick') inv.transferItem(5, playerInventory) will transfer any item from that slot into the player inventory

#

but wait

#

is it will transfer the item to a random player or for the nearest player?

oblique heath
#

where are you getting the inventory from?

sage portal
#

Is there a way to save and edit multiple arrays per player, or are we just forced to keep track of dozens of dynamic properties?

valid ice
sage portal
#

Never tried a method like that before, I'll have to look into it

untold magnet
frozen vine
oblique heath
untold magnet
#

im so tired

distant tulip
frozen vine
distant tulip
untold magnet
oblique heath
untold magnet
frozen vine
distant tulip
frozen vine
#

in the game it looks like this

untold magnet
oblique heath
#

I'm asking if you are using any of those options

untold magnet
#

i don't think so

oblique heath
#

do you want the item to be transfered to nearest player?

distant tulip
untold magnet
#

I'll show u a video as an example

oblique heath
#

ok

frozen vine
oblique heath
#

the slot is an "output slot" correct?

untold magnet
#

discord is glitching for me

#

i literally can spam messages

untold magnet
oblique heath
untold magnet
#

i mean the player cannot place items there, if the player did place the items they will be canceled or dropped

#

or something

distant tulip
#

btw i think doing most of those stuff from the entity json would have been so much better

distant tulip
#

timer and calling script when needed
just my thought so nvm

untold magnet
#

hmm,

#

transferItem β†’ when a player place the item there, it will transfer the item back to the same player

#

or, just drop any items inside that slot

oblique heath
#

how will you prevent duplication exploit

untold magnet
#

transfer the item will not be a problem right?

oblique heath
#

maybe it will work

untold magnet
#

just transfer the item from the entity to the player who is placed that item there

#

hmm

#

i think dropping the item will be better

#

gosh, nvm wait

#

i found a good way

distant tulip
#

just make a slot for the result?

untold magnet
#

making it has a placeholder - locked

untold magnet
#

it shouldn't accept items

distant tulip
#

that what json ui is for...

untold magnet
#

i know i can lock the slot using UI

#

but when it has a output, how can i take it off?,

#

if the slot is locked

distant tulip
#

can't you prevent just adding items?
look at the furnace ui

untold magnet
distant tulip
#

you will need to look at that panel and see what that slot is using
also off-topic

untold magnet
# distant tulip you will need to look at that panel and see what that slot is using also off-top...
"furnace_output_panel": {
    "type": "panel",
    "size": [ "50%", "100%" ],
    "anchor_from": "top_right",
    "anchor_to": "top_right",
    "controls": [
      {
        "[email protected]_item": {
          "anchor_from": "left_middle",
          "anchor_to": "left_middle",
          "size": [ 26, 26 ],
          "$cell_image_size": [ 26, 26 ],
          "offset": [ 20, 0 ],
          "$item_collection_name": "furnace_output_items",

          "$focus_id": "furnace_output_item",
          "$focus_override_right_binding_type": "none",
          "$focus_override_right": "FOCUS_OVERRIDE_STOP",
          "$focus_override_left_binding_type": "none",
          "$focus_override_left": "furnace_fuel_item"
        }
      }
    ]
  },```ui stuff hurts
distant tulip
#

change the vars one by one and test and see πŸ€·β€β™‚οΈ
anyway move to the json channel

untold magnet
#

maybe tomorrow

thorn ocean
#

Does anyone know if system.runJob allows for returning values from a function?

distant tulip
deep quiver
fiery solar
thorn ocean
abstract cave
#
let itemList = ["minecraft:diamond_axe",
    "minecraft:iron_axe",
    "minecraft:netherite_axe"]

world.afterEvents.itemUseOn.subscribe((data) => {
    const player = data.source
    const item = data.itemStack
    const block = data.block
    const itemId = item.typeId

    for (let ItemsID of itemList) {
        if (itemId.includes(ItemsID) && block.typeId === "minecraft:grass_block") {
            player.runCommand("/give @s diamond")
        }
    }
})```
Why does the script not work
Its meant to give the player a diamond if the player rightclicks on grass with an axe
can anyone help
thin steeple
# abstract cave ```js let itemList = ["minecraft:diamond_axe", "minecraft:iron_axe", "mi...

const itemList = ["minecraft:diamond_axe", "minecraft:iron_axe", "minecraft:netherite_axe"];

world.afterEvents.itemUseOn.subscribe((data) => {
  const player = data.source;
  const item = data.itemStack;
  const block = data.block;

  for (const aitem of itemList) {
      if (item?.typeId === aitem && block.typeId === "minecraft:grass_block") {
          player.runCommand("/give @s diamond")
      }
  }
})
#

try that

abstract cave
thin steeple
#

you could also use the array includes method to make things short, but i chose not to add that to your script.

abstract cave
thin steeple
abstract cave
thin steeple
abstract cave
thin steeple
# abstract cave nope
const itemList = ["minecraft:diamond_axe", "minecraft:iron_axe", "minecraft:netherite_axe"];

world.afterEvents.itemUseOn.subscribe((data) => {
  const player = data.source;
  const item = data.itemStack;
  const block = data.block;

  for (const aitem of itemList) {
      if (item?.typeId === aitem && block.typeId === "minecraft:grass_block") {
        player.getComponent("inventory").container.addItem(new ItemStack("minecraft:diamond", 1))
      }
  }
})

try that instead

#

i think it was the command that wasnt working

fiery solar
# thorn ocean How do I do that?

It depends what you want to do, there's lots of ways to pass data around.

Here's a basic example of a function that gets all the Air blocks in a cube using runJob and returns a promise that resolves to those blocks.

function getAirBlocksInRadius(dimension: Dimension, origin: Vector3, radius: number): Promise<Block[]> {
  return new Promise((resolve) => {
    const generator: () => Generator<void, void, void> = function* () {
      const airBlocks: Block[] = [];
      for (let x = -radius; x <= radius; x++) {
        for (let y = -radius; y <= radius; y++) {
          for (let z = -radius; z <= radius; z++) {
            const location = { x: origin.x + x, y: origin.y + y, z: origin.z + z };
            const block = dimension.getBlock(location);
            if (block?.isAir) airBlocks.push(block);
            yield;
          }
        }
      }
      resolve(airBlocks);
    };
    system.runJob(generator());
  });
}

Usage: const airBlocks = await getAirBlocksInRadius(player.dimension, player.location, 10);

abstract cave
distant tulip
thin steeple
#

try that

#

i agree, itemUseOn can be pesky sometimes

abstract cave
#

doesnt work, guess ill just not use itemUseOn

thin steeple
#

it worked just fine for me

abstract cave
thin steeple
abstract cave
# thin steeple

hmm, if i try it with the .includes part, it doesnt work
but without it, it works

north rapids
#

Is it possible to keep the Actionform open even after choosing an option?

north rapids
abstract cave
rose light
#

Is there a way to make a particle appear for only 1 exclusive player?

thorn flicker
#

its in beta

rose light
oblique heath
thorn flicker
thin steeple
thorn flicker
#

1 exclusive player

thin steeple
#

well he said for 1 player

thorn flicker
#

as in, only 1 player can see it.

thin steeple
#

ok chill out

thorn flicker
thin steeple
neat hazel
#

Why this error?

import * as mc from "@minecraft/server"
import * as hash from "./hash.js"

mc.system.runInterval(() => {
  for (const player of mc.world.getPlayers()) {
LINE 7 -->    const hand = player.getComponent("minecraft:inventory").container.getItem(player.selectedSlot)
    if (hand && hand.typeId === `minecraft:diamond`) {
      player.onScreenDisplay.updateSubtitle(
        `Test`
      )
    }
  }
}, 5)
oblique heath
#

LINE 7 -->

oblique heath
neat hazel
neat hazel
distant gulch
#

why in the hell does it keep saying this?

shy leaf
distant gulch
#

thats why i have if (TickTime === undefined)

shy leaf
#

it also might be a string

#

try typeof to check if its a string or number

distant gulch
#

def not the issue, even with removing the TickTime stuff it still throws an error

shy leaf
#

oof

#

that error is seriously painful to resolve, ive experienced it before

distant gulch
#

i've never had this issue so i have no clue :(

shy leaf
#

maybe do you have try catch somewhere?

#

since its not pointing to anywhere

distant gulch
shy leaf
#

no i was asking if you had it anywhere

#

is that the one though

distant gulch
#

fixed it

#

idk what the issue was

#

i just re did the entire menu

shy leaf
#

gg

#

i dunno why that error happens sometimes

distant gulch
#

yeah it can be annoying

subtle cove
neat hazel
sour narwhal
#

Yo

sour narwhal
#

Can someone help me in something?

#

Plsss

lone thistle
sour narwhal
#

Either im too dumb or no one knows how to do that

sour narwhal
#

Plz

slim spear
#

How would i update a water block immediately after setting it?

#

i'm setting it like this: block.setPermutation(BlockPermutation.resolve("minecraft:water"))

oblique heath
#

why not set use .setType?

oblique heath
slim spear
oblique heath
#

yes...

slim spear
#

does that update the block?

oblique heath
#

not sure

slim spear
#

it does not

#

making a bucketable fish

oblique heath
#

rip

oblique heath
slim spear
#

I shall try that

oblique heath
#

just tested it

slim spear
#

ty

hardy cedar
#

Is it not possible to use multiple addons which have scripts??

honest spear
#

it is possiblle

hardy cedar
honest spear
#

just add more packs zo you world πŸ‘

hardy cedar
#

The scripts don't work

#

Only the one at the top does

random flint
#

what kind of "scripts"

distant tulip
#

or invis blocks and remove it
or just air?

slim spear
distant tulip
#

in the source block?

slim spear
#

Ye

distant tulip
#

you can't pick that up

slim spear
#

?

#

I was able to

distant tulip
#

huh

slim spear
#

When I set flowing_water it acted like a source block too

distant tulip
#

weird

untold magnet
#

#1291532531489046551 bao_foxxo_blank

hardy cedar
ruby haven
#

Is it possible to recreate the behavior of fishing rod but instead of pulling the entities it pulls you and I also sticks in blocks

distant tulip
sage sparrow
#

hi there, on the playerLeave I cannot get the dimension and location the player was?

random flint
distant tulip
#

not sure what are you using that for but keep in mind that may not trigger if the game is force closed

random flint
#

I guess you can periodically save each data with system.runInterval with a bit cost of performance

thorn ocean
#

LOL, just realized that now there is dyeable component for items, we need a method in scripting to manipulate such values.

thorn ocean
honest spear
distant tulip
distant tulip
#

thanks

last latch
#

technically there is no method to destroy blocks / get drop from blocks using script api (not including commands) right?

honest spear
#

why in theory?

#

bc its not module for addon development

#

well at least not now

last latch
untold magnet
#

well well well. . .

#

only one last thing is left for the forge block

#

adding custom sound effects

last latch
#

i spent like 10 hours

#

but i have it (partially)

#

now
sounds, particles, enchants and shears!

#

😭

untold magnet
#

?

untold magnet
frozen vine
#

Is it possible to detect when the player dies?

last latch
#

so i can get a drop from a block

untold magnet
#

i already have thatbao_ext_toldyouso

last latch
#

really?

untold magnet
#

i literally made a whole system for it

#

a couple months ago

#

when i was new at scripting

last latch
#

nice
but does it have all tools?

untold magnet
#

like having a custom destroy speed?

#

that is possible to do using the block.json

last latch
#

nah only which tool drops this item from this block

untold magnet
#

fortune is applied too, u can use fortune and u will have different drop amounts

#

same with silk touch

#

if the ore required iron tier +
and u trying to break the block using a silk touch shears, it will not drop the block.

last latch
#

nice

last latch
#

the only downside that this map lags my IDE (vsc) alot

#

i will improve it and post it on github

untold magnet
#

i already done that ;>

#

for now i will not update it

#

I'll be focusing on making the addon functionality

last latch
# untold magnet u should make it not dropping anything if the player are in creative mode

ik i just made a quick script that retrieves the drop

world.afterEvents.playerBreakBlock.subscribe(({ itemStackBeforeBreak: itemStack, player, brokenBlockPermutation: { type: { id: typeId } }, dimension, block: { location: { x, y, z } } }) => {
    const usedTool = tools.includes(itemStack?.typeId.replace("minecraft:", "")) ? itemStack.typeId : "fists";

    const drops = lootTable.get(typeId).tools.get(usedTool.replace("minecraft:", ""));

    for (const drop of drops)
        dimension.spawnItem(new ItemStack(drop), { x: x + 0.5, y: y, z: z + 0.5 })
});```
untold magnet
#

anyways

#

#1291848665052483614

untold magnet
#

entityDie i guess

last latch
#
import { Player, world } from "@minecraft/server";

world.afterEvents.entityDie.subscribe(({ entity }) => {
    if (entity instanceof Player) world.sendMessage(entity.name + " died");
});```
last latch
#

is there a block which drops 2 items when mined?

bright torrent
#

Say I want to make a particle persist until I want to remove it. Basically, I want a 2D graphic to persist until I'd like to remove it. Is the only way to attach it to a dummy entity/make it part of the entity's animation, and then remove the entity when I want to remove the particle?

untold magnet
#

just put it twice

thorn flicker
#

he wasnt asking how to do it

#

he was asking if there was a vanilla block that did that

untold magnet
#

oh

#

yah my bad

thorn flicker
#

lol

untold magnet
thorn flicker
#

also hey

#

my dynamic property thing was trash apparently?

untold magnet
#

?

thorn flicker
#

Ive gave you code about a dynamic property not that long ago

#

you had issues with it being slow or something

untold magnet
#

yes it is slow as hell

thorn flicker
#

I dont see how

untold magnet
#

im using 3 different dynamic properties at the same time

#

i have to increase the dynamic property number at the same time for each one

#

which was sooo slow

thorn flicker
#

πŸ€·β€β™‚οΈ

#

you found a fix though?

untold magnet
#

in fact, im using 4 different dynamic properties

untold magnet
thorn flicker
#

whats the fix? im curious.

untold magnet
#

i used my method

#

if (1) 2
if (2) 3
if (3) 4

thorn flicker
#

bruh

untold magnet
#

this was way faster

#

way

thorn flicker
#

I still cant think of a reason why it would be slow

#

makes no sense

untold magnet
#

thats why i changed it

thorn flicker
#

you are just retrieving the current value, and adding onto it...

untold magnet
#

everything is 200% right, but still slow and having issues with the timer

thorn flicker
untold magnet
#

i removed the delay from the interval, it should spam it

#

i did some tests

#

console.warn outside the property thing

#

and console.warn inside the property thing

#

it should spam it fast, but it not

thorn flicker
#

idk

#

I guess it was just too much

last latch
last latch
thorn flicker
#

answer to your question: no

last latch
#

oh nice

thorn flicker
#

lol

#

unless... you mean like, fortune

last latch
#

just two different items

#

like one apple and one stick

thorn flicker
#

different items, no.

last latch
#

nice

thorn flicker
#

why?

untold magnet
thorn flicker
#

I meant fortune

#

mb

last latch
# thorn flicker why?

i am trying to make a map with every loot from every vanilla block with every fortune level and silktouch

#

already made one just with pure tools and not randomized drop rate of ores and other alike blocks*

lone thistle
last latch
#

unless you count setblock ~~~ air destroy

lone thistle
#

Try spawning items on break block?

distant tulip
#

the loot table command have the blocks drop?

last latch
lone thistle
#

loot table or dimension spawn item

last latch
#

i am making a map with every block drop

#

i need it to spawn items

thorn flicker
#

I dont understand what you are trying to do really

last latch
#

||you cant (using methods)||

terse tide
#

Its possible to make when i click in a block if i have a tag the block switch?

thorn flicker
#

you mean when the block get's turned to air without the player breaking it

#

I see.

lone thistle
#

playerBreakBlock beforeEvent + enchantable component of the held item

thorn flicker
last latch
lone thistle
#

Ah alright

last latch
last latch
#

using new Map<k, v>()

thorn flicker
#

or just have a destroy method on the block class

#

thats it

#

nothing fancy

#

block.destroy()

last latch
#

yeah,

last latch
#

it is possible to switch a block whenever you interact with a block with a specific tag

thorn flicker
#

when you click it, just use the setType() method.

distant tulip
thorn flicker
#

we are WISHING for it

terse tide
#

how?

last latch
#

the funniest part is that my undone map is already at 38k lines 🀣

distant tulip
thorn flicker
#

assuming the variable for player, is player, and for block, its block ofc.

terse tide
#

I know that

thorn flicker
terse tide
#

but when i click

#

what function do i use for when i click?

thorn flicker
#

depends

#

do you want it to trigger when you have an item, or empty hand and item?

terse tide
#

empty

thorn flicker
#

custom components or world events

#

if its a vanilla block, it needs to be a world event

#

playerInteractWithBlock

terse tide
#

Api version?

thorn flicker
#

for playerInteractWithBlock, you need beta apis.

#

should come out in stable 1.21.40

terse tide
#

Thanks

thorn flicker
# terse tide Thanks

if its a custom block, you could use custom components, which is in stable rn.

untold magnet
#

ugh

thorn flicker
untold magnet
#

im getting more issuesbao_foxxo_blank bao_foxxo_blank

last latch
#

It is sometimes fun to look at #1046947779118895114

#

How some people do amazing stuff using Json UI, or code custom blocks with their own mechanics or code helpful utils

oblique heath
#

yep

zinc flax
#

Is running commands inside scripts better than running commands through tick.js functions?

thin steeple
#

use the native methods

terse tide
#

Its possible to open a container with playerInteractBlock?

oblique heath
#

no

fiery solar
bright torrent
#

What are the use cases for scriptevent commands?

subtle cove
abstract cave
#

Is there a way to detect when a player right clicks an entity with an item? using scripts

tiny tartan
abstract cave
tiny tartan
shy leaf
#

whar

#

but its

thorn flicker
abstract cave
#

[Scripting][error]-Unhandled promise rejection: TypeError: cannot read property 'subscribe' of undefined

[Scripting][error]-Plugin [Extractinator - 1.0.0] - [main.js] ran with error: [TypeError: cannot read property 'subscribe' of undefined    at <anonymous> (pulverized_copper.js:34)

world.afterEvents.playerInteractWithEntity.subscribe((data) => {
    const player = data.player;
    const item = data.itemStack
    const entity = data.target

    if (item.typeId === "splus:syringe" && entity.typeId === "minecraft:creeper") {
        player.runCommand("/say I extracted your dna")
    }
})

Why do i receive this error

shy leaf
abstract cave
#

crap

tiny tartan
#

it will get stable in next update iirc

shy leaf
abstract cave
#

is there any way to replicate this

thorn flicker
#

edit the creeper json or use getEntitiesFromViewDirection() with itemUse world event

oblique heath
#

☠️

abstract cave
thorn flicker
#

also 1.14.0 is the latest

shy leaf
#

its right there??

tiny tartan
#

iirc s1 said that event signals are stable but event it self is still beta for some reason but not sure

thorn flicker
#

ive seen people say it'll come out in 1.21.40

#

along with playerInteractWithBlock

shy leaf
thorn flicker
#

same thing on stirante

oblique heath
#

if its not here then its not in stable

shy leaf
#

what in the bloody hell

thorn flicker
#

yeah

#

just wait for 1.21.40

valid ice
#

s' been beta forever at this point

shy leaf
#

so the game has been gaslighting me the whole time???

thorn flicker
#

the docs have

#

lol

shy leaf
#

ive been using it without issues so i thought it was stable the whole time

#

oml

hybrid island
#

can someone give me code like when a player gets out of the cordinates
420 62 271 269 62 361
then i can do someting

subtle cove
#
const q = {
    location: {x: 269,y:-60,z:271},
    get volume() {
        return {x: 420 - this.location.x, y:500, z:361, 
- this.location.z} 
    } 
}
if (!player.matches(q)) {
    //is outside
} 
oblique heath
#

ItemComponentUseOnEvent seems to never fire for custom items that have the minecraft:is_shovel tag...

urban goblet
#

is there a way to pass info from scriptAPI to attachable?

#

I want to use animation controllers to play different animations base on data from scriptAPI

#

So is there a way for scriptAPI pass data to molang then in RPAnim, use query to play animation base on the molang

unkempt siren
#

is it possible to write/read files with script api?

prisma shard
#

no

#

Oh, then you can't

#

but you cant write files with sceipt api

unkempt siren
#

nah i meant text or json files

#

alr

prisma shard
subtle cove
halcyon phoenix
#

is it possible to trigger uis in JS? like a simple regen bar

halcyon phoenix
halcyon phoenix
halcyon phoenix
distant tulip
halcyon phoenix
#

ahh I see

#

thanks minato

#

annyways dare enchantments just lore?

halcyon phoenix
#

found this: ```js
enchantments.addEnchantment({ type: new EnchantmentType(MinecraftEnchantmentTypes.FireAspect), level: 1 });

but doing this: ```js
enchantments.addEnchantment({ type: FireAspect), level: 1 });

is the same right?

keen folio
#

will this work?

const armor  = player.getComponent("equippable")?.getEquipment("Armor");```
halcyon phoenix
#

Body, Head, Chest etc....

keen folio
halcyon phoenix
#

and check each

#

whatcha tryna do?

halcyon phoenix
keen folio
#

resolved

distant tulip
#

define an array with all the armor parts and map the items

halcyon phoenix
distant tulip
halcyon phoenix
#

so I need to do
MinecaftEnchantmentTypes?

full brook
halcyon phoenix
halcyon phoenix
halcyon phoenix
distant tulip
#

what are you trying to do

amber granite
#

What s new ?

untold magnet
#

sheeeeesh, 156 lines for the forge system

#

its finally finished

keen folio
# distant tulip define an array with all the armor parts and map the items
const armorSlots = ['head', 'chest', 'legs', 'feet'];
        for (const slot of armorSlots) {
            const armor = dEntity.getComponent('equippable')?.getEquipment(slot);
            if (!armor) continue;

Error:
[Scripting][error]-TypeError: Native type conversion failed to argument [0] expected type: EquipmentSlot at <anonymous>

subtle cove
#

Head, Chest etc

untold magnet
#

12 freaking days of making only one blockbao_doggo_smug

#

day 1: model + texture
day 2: unfinished UI
day 3 ~ day 12: functionality + UI

halcyon phoenix
subtle cove
#

grindstone...

halcyon phoenix
#

its an item

#

instead of a block

#

off hand item

untold magnet
#

idk

halcyon phoenix
#

yeah extract

#

also I don't know how grindstone works πŸ™‚

untold magnet
#

grindstone just removes the enchantment and gives u some XPs

halcyon phoenix
#

yeah never used it once πŸ™ƒ

#

but i'm tryna make a portable disenchanter that uses amethyst as fuel

#
    /// USES CHATSEND AFTER 
        let mainhand = sender.getComponent("equippable").getEquipment("Mainhand")
        let enchants = mainhand.getComponent(ItemEnchantableComponent.componentId)
        enchants.addEnchantment({type: "minecraft:fire_aspect", level: 1})
        sender.getComponent("equippable").setEquipment("mainhand", mainhand)
#

hilp 😦

last latch
#

One block has more than 1 different drop

#

one out of hundreds

wheat condor
#

is there something to know if a chest state is opened or closed?

subtle cove
#

apple, sapling stick

halcyon phoenix
#

heyhey how do you check if an inventory slot is empty?

subtle cove
#
const itemSlot = container.getSlot(13)
if (!itemSlot.hasItem()) {
  //no item
}
last latch
#

i was talking about netherreactor

#

lol

subtle cove
#

;-;

untold magnet
#

why?;
entity?.triggerEvent('exe:despawn')

#

this is the full line:
system.runTimeout(() => { if (block?.typeId !== 'my:block' && block?.isValid() === true) { entity?.triggerEvent('exe:despawn') } }, TicksPerSecond * 0.1);

subtle cove
#

entity.isValid()

#

why despawn event when there's entity.remove()

halcyon phoenix
#
if (item.typeId == "minecraft:book") {
  const enchants = item.getComponent("enchantable")                
  enchants.addEnchantment({type: "minecraft:fire_aspect", level: 1})
}

is this the correct way to add enchants?

untold magnet
subtle cove
#

search addEnchantment here

halcyon phoenix
#

here?

subtle cove
#

yeah, to see other's code samples

halcyon phoenix
#

dude what....

subtle cove
#

mhm

halcyon phoenix
#

lol

#

Thanks by the way

halcyon phoenix
#

why did the book not turn in enchanted

#

dang mending is now stackable

subtle cove
#

its likely abug that doesnt auto change the book into enchanted_book

pliant kite
#

Is there an event that updates every tick and can detect player moving?

random flint
#

What version is dat

halcyon phoenix
halcyon phoenix
#

I should post this to PheonixSC subreddit

random flint
#

Then "minecraft:enchanted_book" is a thing?

#

xd

subtle cove
#

youd have to make a function to check movements every tick

halcyon phoenix
halcyon phoenix
#

never used it

subtle cove
#

velocity changes either when player moved or got-moved

halcyon phoenix
#

does it output 0 when not moving?

subtle cove
#

0,0,0 as xyz

#

yes

halcyon phoenix
#

then that could work i gues as a afk detector

random flint
#

Will an entity (especially a player) stop getting pushed by water flow if I set their underwater movement attribute to zero?

subtle cove
#

dunno, test it

random flint
#

Mmm, yes, let me test on Lava movement too

idle dagger
#

How to make player fall after his β€œmayfly” ability disabled? Because when I disable it player still will be in fly mode and will not fall down until he disables fly

last latch
#

lol

last latch
last latch
hazy nebula
#

Anyone know how to crack the copyright key of word office 2016 please help me!

open urchin
#

no

distant tulip
#

πŸ—Ώ

random flint
open urchin
#

this is a minecraft add-on development server

distant tulip
thin steeple
nocturne berry
#

Is it possible to detect empty entity slot?

nocturne berry
pliant kite
#

how to detect player jump?

thin steeple
pliant kite
fiery solar
pliant kite
fallow rivet
#

Dynamicproperty?

static nebula
#

Does anyone know how I can make a script that counts how many blocks an entity has walked?

winter plaza
#
import * as mc from "@minecraft/server";

mc.system.afterEvents.scriptEventReceive.subscribe(event => {
  for (const player of mc.world.getPlayers()) {
    //if(!event.id.startsWith("test:")) return;
    const wg = event.id.split("wg:")[1];
    const eventEntity = event.sourceEntity;
    const player2 = event.sourceEntity;
    switch (wg) {
      case "clone":
        clone(eventEntity);
      break
    }
  }
});

export function clone(eventEntity) {
  for (const player of mc.world.getPlayers()) {
    const plr = player.nameTag == `${eventEntity.nameTag}`;
    eventEntity.runCommand(`event entity @s wesl3y:hair.${plr.getProperty("wesl3y:hair")}`);
    console.log(`plr`);
  }
}
#

help

last latch
#

Are Maps or objects faster?

oblique heath
#

I'd imagine objects are faster

north depot
#

hi bao_bee_happy
con i ask something in here ?
its about block.location....
πŸ‘‰ πŸ‘ˆ

fiery solar
last latch
fiery solar
north depot
#

block.dimension.spawnParticle("minecraft:crop_growth_emitter", block.location);

#

how can i change the block.location?

#

const { x, y, z } = block.location;

lone thistle
north depot
#

i want the particles appear above the block...