#Script API General

1 messages · Page 44 of 1

thorn flicker
#

maybe when that comes they could add a way to check for ticking areas, could be cool

dense skiff
#

annoying... i thought i noticed you could get the feedback from the command at some point or was i mistaken

#

Btw is there any other good way to load just a single chunk before I go try stuff lol

thorn flicker
#

I guess you could try to use that to tell how many ticking areas there are

#

maybe use a world dynamic property, and increment this property value everytime the command is successful?

sour flame
dense skiff
#

Someone could definitely make their own little wrapper for the tickingarea commands so you could access them more like an api

#

Nevermind the commandResult for a successful tickingarea placement is the same as an unsuccessful one

oak lynx
#

Item json minecraft:interact_button triggers itemUse event right?

fiery solar
slow walrus
#

await_chunks isn't super optimised since the game has to check all the blocks in the volume, but the others are fine afaik

lone sequoia
#

hey guys im developing a framework to create addons at the speed of light, does anyone wanna try it out?

tight plume
slow walrus
#

lol

subtle cove
#

How heavy are bytes

slow walrus
spark topaz
#

Petition to start forcing everyone to use typescript

slow walrus
#

they should replace QuickJS with deno

coral ermine
#

What if entity location chunk is not loaded and it keep spamming “Failed to get property location at <anonymous>”

#

const { x: ex, y: ey, z: ez } = entity?.location;

subtle cove
#

Cus entity is not valid

spark topaz
#

It's not loaded so ther is technically nothing there

coral ermine
subtle cove
#

Check again...

fiery solar
subtle cove
#

Ive only seen "Failed to get property" errors when an object isn't valid, in script api

coral ermine
#

Well how to make it do not spam in console until chunk is loaded?

subtle cove
#

-# hence entity.isValid()

slow walrus
#

@warm mason lazy coding 🤷‍♂️

dense skiff
dim tusk
#

Having no internet sucks but also quite fun

#

I slept 8 hours because of that

dim tusk
jolly citrus
#

I want to switch to ts but I do not have the motivation to rewrite 30 files that I’ve created over the span of a year

#

I have no idea what is going on in half of them because the code is so messy

dim tusk
#

Rewrite them one by one 🤷

jolly citrus
#

Even opening them to make small edits is painful to my brain

#

no idea what all the variable names are supposed to mean unless I look for the definition and everything is hardcoded

slow walrus
#

the best time to clean up tech debt is right now. Don't let it compound, eventually you or someone else will have to do it, and it'll just get worse and worse

dim tusk
tiny tartan
#

how do i show action form when player first time spawns i have tried playerSpawn event with initialSpawn but when i load the world it doesn't show any form, should i use system.runTimeout?

quick shoal
#

if (response.canceled && response.cancelationReason === 'userBusy') return form(player)

tiny tartan
#

Thnx

dim tusk
#

Quick question... It's not possible to get the file name inside the folder right?

#

Out of curiosity since I could do it on non mc js

neat hound
#

Probably Not and no one should be able to do anything in FileSystem ever. Can you imagine the havoc?

dim tusk
chilly fractal
dim tusk
#

My mind is mixed with non and mc js lmao

#

Looks like I'll be making a python that converts multiple json into an object or map

#

sigh

chilly fractal
#

You won't be able to, you can't use require as mc doesn't use commonJS and you can't import json or other files because they don't "EXPORT" anything. And there is no file manager system in mc. Imagine being able to access the Player's world directly from your script lmao

#

The havoc

dim tusk
dim tusk
chilly fractal
#

Coddy xxxx Chaos?

#

W

dim tusk
#

So umm, idk if this is script related shii but is it normal that fishing hook doesn't have an owner?

#

Like when the player used a fishing rod to spawn the fishing hook it's normal that it doesn't have an owner instead of the player who spawned it?

distant tulip
#

why should it?

dim tusk
#

🤷

#

Why shouldn't?

distant tulip
#

it doesn't give the thrower any credit directly

chilly fractal
dim tusk
chilly fractal
#

Assault on minor and hit and run

#

And it is on the loose, if you find anything about that fishing rod please Head to the nearest fish police station to report it

chilly fractal
dim tusk
#

Damn, looks like I'll be using !player.isOnGround instead of player.isFalling

chilly fractal
#

Anyway gtg

dim tusk
#

the isFalling isn't triggered when the player doesn't move an inch example I'm afk and I tp'd myself 20 blocks above, the isFalling isn't triggered ughh

chilly fractal
chilly fractal
dim tusk
chilly fractal
dim tusk
#

bang splat

#

Why did you kill him, officer we need information on about his friends whereabouts

subtle cove
#

Hopefully it's not the weird guy

tight plume
#

why is there conversation like that

dim tusk
sage sparrow
#

hi there, do someone know if there is a limit of characters for server form title field?

sage sparrow
#

I mean the limit (if there is any) on that formUI.title(titleMsg)
I m using this field as codes/instructions for my custom UI, so I want to know if there is any limit on that to avoid going over

tight plume
#

No but it will lag

distant tulip
#

i do however remember it lagging in normal forms

sage sparrow
#

well it is fine, is a on demand UI, it will not keep updating so the lag is not a problem, but still I maybe was too concerned about because my length is still under ~200 characters, so I have space to work yet, thx

crude flame
#

hi, is it posible to apply knockback to a player if he is one block above an entity?

tight plume
#

Why BlockComponentPlayerInteractEvent player argument either returns Player | undefined? Isn't it suppose to be only player since what other things may interact with this?

elfin rose
#

help

#
world.afterEvents.playerBreakBlock.subscribe(({ player }) => {
    const blocksMinedObjective = world.scoreboard.getObjective("blocksMined");
    const moneyObjective = world.scoreboard.getObjective("money");

    if (!blocksMinedObjective || !moneyObjective) return;

    // Get current blocks mined
    let currentBlocks = 0;
    try {
        currentBlocks = blocksMinedObjective.getScore(player);
    } catch {
        currentBlocks = 0;
    }

    // Increment and update blocks mined
    currentBlocks += 1;
    blocksMinedObjective.setScore(player, currentBlocks);

    // Update action bar
    player.onScreenDisplay.setActionBar(`${currentBlocks} blocks mined`);

    // Check for quest completion
    miningQuests.forEach((quest) => {
        if (currentBlocks === quest.blockTarget) {
            let currentMoney = 0;
            try {
                currentMoney = moneyObjective.getScore(player);
            } catch {
                currentMoney = 0;
            }

            // Reward the player
            const newMoney = currentMoney + quest.reward;
            moneyObjective.setScore(player, newMoney);

            player.sendMessage(
                `§aQuest Completed! You mined ${quest.blockTarget} blocks and earned $${quest.reward}.`
            );
        }
    });
});

drifting ravenBOT
#
How To Ask Good Questions

Be specific and include relevant details about the question upfront.

  • What are you trying to accomplish?
  • If you have code, which part is not working? Any content logs?
  • What have you already tried?
  • Have you searched the Bedrock Wiki?

https://xyproblem.info/

gaunt salmonBOT
#

Suggestion for @elfin rose

Description
Gets the score recorded for {displayName} on {objective}

Parameters
player: Player or entity on the scoreboard
objectiveId: String Objective Identifer to get from
rNull: Boolean If the return should be null if its not found or 0.

returns
Number - Score that Was recorded for {Player} on {Objective}

example

getScore(player, "objective"): number

Credits
These scripts were written by iBlqzed

#

Description
A wrapped function that set/add/remove entity score and fetch scoreboard objective display.

  • entity: Entity Entity's scoreboard to change
  • objectiveId: string Objective to apply the score to.
  • score: number Score value
  • action: ScoreboardAction Decides whether to add, remove, or set score to entity (default = set)
  • fetch: boolean Fetch scoreboard objective display (default = true)

Usage
Add score:

import { setScore, ScoreboardAction } from "./index";
setSco
```...
#

ScoreboardM
A enhanced tool for managing scoreboards

Description
How to use?
This example will explain it.

import { ScoreboardM } from "index.js";
ScoreboardM.newObj("id","val") //This is for assigning new objective to the world.
ScoreboardM.setObj("id","val2") // this changes 
ScoreboardM.getObj("id") //This returns the Objective with given identifier.
ScoreboardM.hasObj("id") // This Returns True Or False Telling whether the objective exist or not.
ScoreboardM.delObj("id
```...
chilly fractal
#

Please use these commands in #bot-usage

#

Not in here

elfin rose
#

oh ok

chilly fractal
#

And I wouldn't wanna judge but that code looks awfully like AI written code.

tight plume
chilly fractal
#

Who murdered Mr villager?

chilly fractal
#

It is for sure him because he ran away now.. we can't get his .id now...

subtle cove
chilly fractal
chilly fractal
chilly fractal
chilly fractal
#

Or maybe the documents are just high on mc vodka potions

jolly citrus
#

i am making the grand switch to ts today

#

34 files to be fixed

#

i wish you could use a combination of ts and js imported files in script api

crude flame
#

i want to make flying jellyfish on which you get knocked If you are over it(Like a slime Block)

chilly fractal
#

Literally copy paste

#

Just edit the knockback values to your suiting

autumn seal
#

You say like a slimeblock are you trying to get the motion of the player when they fall on top of it and work off that?

crude flame
subtle cove
#

entity.json component, yes
but not in script api

crude flame
autumn seal
#

I think environment sensor has a distance_to_nearest_player filter

#

then you can have an event ran if a player is within certain distance ("event:player_near") for example

#

this is more of an #1067869022273667152 thing

#

but you could then just test for the event in the script by using world.afterEvents.dataDrivenEntityTrigger and filter for the event by using something along the lines of event.eventId === "event:player_near"

crude flame
#

Ok, i'll try it. Thank you

autumn seal
#

if it doesnt work lmk ill see if I was wrong about something

crude flame
#

I will try it in Like 3h.

stark kestrel
#
world.afterEvents.entityHurt.subscribe((eventData) => {
    const hurtEntity = eventData.hurtEntity
    const damagingEntity = eventData.damageSource.damagingEntity
    const item = damagingEntity.getComponent("equipment").getEquipmentSlot("Mainhand")
    const LIGHTNING_CHANCE = item.getDynamicProperty('[lightn]');

    function shouldStrikeLightning() {
        return Math.random() * 100 < LIGHTNING_CHANCE;
    }

    if (!hurtEntity || !damagingEntity) return;


    if (damagingEntity.typeId === 'minecraft:zombie') {

        if (shouldStrikeLightning()) {

            const { x, y, z } = hurtEntity.location;
            world.getDimension('overworld').runCommandAsync(`summon lightning_bolt ${x} ${y} ${z}`);
        }
    }
});```
#

any1 knows what im doing wrong

warm mason
stark kestrel
#

then how can i fix it?

warm mason
stark kestrel
#

thanks

stark kestrel
# warm mason
world.afterEvents.entityHurt.subscribe((eventData) => {
    const hurtEntity = eventData.hurtEntity
    const damagingEntity = eventData.damageSource.damagingEntity
    const item = damagingEntity.getComponent("equipment").getEquipmentSlot("Mainhand")
    const LIGHTNING_CHANCE = item.getDynamicProperty('[lightn]');

    function shouldStrikeLightning() {
        return Math.random() * 100 < LIGHTNING_CHANCE;
    }

    if (!hurtEntity || !damagingEntity) return;


    if (damagingEntity.typeId === 'minecraft:player') {

        if (shouldStrikeLightning()) {

            const { x, y, z } = hurtEntity.location;
            world.getDimension('overworld').runCommandAsync(`summon lightning_bolt ${x} ${y} ${z}`);
        }
    }
});```
#

like this?

#

thanks

#

oof now i need soemone to test tahnks

#

cannot read property of getEquipment slot

#

of undefined at anonymoyous

#

@warm mason

#

uh

warm mason
#
world.afterEvents.entityHurt.subscribe((eventData) => {
    const entity = eventData.hurtEntity
    const player = eventData.damageSource.damagingEntity
    if (!entity || player?.typeId != "minecraft:player") return
    let item = player.getComponent('equippable').getEquipment('Mainhand')

    if (Math.random() < item.getDynamicProperty('[lightn]')/100) {
      entity.dimension.spawnEntity('lightning_bolt', entity.location)
    }
});
stark kestrel
warm mason
stark kestrel
#

This one?

warm mason
stark kestrel
#

Uh okay

stark kestrel
warm mason
stark kestrel
#

works*

#

thanks, i edited ur script it works

dim tusk
#

God damnit... Why a lot of people asking if I do a commission

distant gulch
#

good idea

pseudo marlin
#

Does anyone know how to make a crafting table script using entity? Simple and compact, please help me

warm mason
pseudo marlin
#

like it was a custom crafting table but using entity

warm mason
#

Why would you use an entity and not a crafting table component in blocks?

pseudo marlin
#

because it will have more slots than normal

distant tulip
#

he is asking for a custom recipe system using entity inventory and json ui

warm mason
#

Although the script itself..

distant tulip
#

he is not asking about the ui
just the detecting of the recipe

#

i guess you can just map the slots to an array and compare that to a recipe?

pseudo marlin
#

bro @distant tulip I sent you a message in private can you answer me

distant tulip
#

can't help you right now, sorry

pseudo marlin
#

Ok

warm mason
#

Use EntityInevntoryComponent to find out what items are currently in a “crafting table” and compare them with the ones you need, if everything matches, then delete them and issue a new item

distant tulip
#

@pseudo marlin how many slots do you have
and what it the output slot index

pseudo marlin
distant tulip
#

💀

pseudo marlin
#

sorry it's a lot right?

distant tulip
#

yeah
anyway is it a grid or what?

warm mason
pseudo marlin
distant tulip
pseudo marlin
wheat condor
#

If someone is interested about a class for the new input info #1319734492478312498 message

dim tusk
#

It took me 25 mins to alphabetical order translated words lmao
-# it's 2am in the morning so pls be chill with me

distant tulip
#

what happen if you set item amount to 0?

elfin rose
#

is there any different method, like tracking block changes via a scoreboard or any subscribe?

distant tulip
dim tusk
#

Wait lemme try...

distant tulip
warm mason
distant tulip
#

thought so

autumn seal
distant tulip
#

@pseudo marlin
not tested

dim tusk
# distant tulip <:bao_icon_entities:937567566442922084>
world.beforeEvents.itemUse.subscribe(({ itemStack, source }) =>{
    if (itemStack.typeId === 'minecraft:diamond') {
        const inventory = source.getComponent('inventory').container;
        system.run(() => {
            itemStack.amount = 0;
            inventory.setItem(source.selectedSlotIndex, itemStack);
        });
    }
});```
#

So umm it throws an error saying not a valid amount and the amount should be 0 to ,255

warm mason
dim tusk
#

My internet is so shit, that it just sends now

distant tulip
#

yeah
good to have that confirmed

dim tusk
distant tulip
warm mason
elfin rose
#
// Player join event
world.afterEvents.playerJoin.subscribe(({ player }) => {
    const playerId = player.name;
    const playerPlot = db.get(playerId);

    if (playerPlot) {
        loadPlot(player, playerPlot.index, playerPlot.coordinates);
    }
});

// Player leave event
world.afterEvents.playerLeave.subscribe(({ player }) => {
    const playerId = player.name;
    const playerPlot = db.get(playerId);

    if (playerPlot) {
        unloadPlot(playerPlot.index);
    }
});
```\
gaunt salmonBOT
# elfin rose ```js // Player join event world.afterEvents.playerJoin.subscribe(({ player }) =...

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 6 errors:

<REPL0>.js:2:43 - error TS2339: Property 'player' does not exist on type 'PlayerJoinAfterEvent'.

2 world.afterEvents.playerJoin.subscribe(({ player }) => {
                                            ~~~~~~

``````ansi
<REPL0>.js:4:24 - error TS2304: Cannot find name 'db'.

4     const playerPlot = db.get(playerId);
                         ~~

``````ansi
<REPL0>.js:7:9 - error TS2304: Cannot find name 'loadPlot'.

7         loadPlot(player, playerPlot.index, playerPlot.coordinates);
          ~~~~~~~~

``````ansi
<REPL0>.js:12:44 - error TS2339: Property 'player' does not exist on type 'PlayerLeaveAfterEvent'.

12 world.afterEvents.playerLeave.subscribe(({ player }) => {
                                              ~~~~~~

``````ansi
<REPL0>.js:14:24 - error TS2304: Cannot find name 'db'.

14     const playerPlot = db.get(playerId);
                          ~~

``````ansi
<REPL0>.js:17:9 - error TS2304: Cannot find name 'unloadPlot'.

17         unloadPlot(playerPlot.index);
           ~~~~~~~~~~

Lint Result

There are no errors from ESLint.

warm mason
#

playerJoin does not have a player property

pseudo marlin
elfin rose
#

hmm yeah

#

didnt think of it

warm mason
granite badger
dim tusk
# elfin rose hmm yeah
world.afterEvents.playerSpawn.subscribe(({ player, initialSpawn }) => {
   if (initialSpawn) {}
});```
#

in playerLeave just use before events not after events

#

If... You're settling something otherwise just use after events

distant tulip
simple arch
#

Any suggestions for my simulated player menu?

warm mason
simple arch
warm mason
#

Yes, like gpt.

elfin rose
#
block.dimension.setBlock(block.location, block.type)
#

anything wrong

gaunt salmonBOT
gaunt salmonBOT
# elfin rose ```js block.dimension.setBlock(block.location, block.type) ```

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 3 errors:

<REPL0>.js:1:1 - error TS2552: Cannot find name 'block'. Did you mean 'Block'?

1 block.dimension.setBlock(block.location, block.type)
  ~~~~~

  @minecraft/server.d.ts:3864:15
    3864         class Block {
                       ~~~~~
    'Block' is declared here.

``````ansi
<REPL0>.js:1:26 - error TS2552: Cannot find name 'block'. Did you mean 'Block'?

1 block.dimension.setBlock(block.location, block.type)
                           ~~~~~

  @minecraft/server.d.ts:3864:15
    3864         class Block {
                       ~~~~~
    'Block' is declared here.

``````ansi
<REPL0>.js:1:42 - error TS2552: Cannot find name 'block'. Did you mean 'Block'?

1 block.dimension.setBlock(block.location, block.type)
                                           ~~~~~

  @minecraft/server.d.ts:3864:15
    3864         class Block {
                       ~~~~~
    'Block' is declared here.

Lint Result

There are no errors from ESLint.

warm mason
#
block.setType('dirt')
elfin rose
distant tulip
# distant tulip

@pseudo marlin
replace

container.setItem(slot, new ItemStack(resultItem.split(" ")[0], Number(resultItem.split(" ")[1])));

with

container.setItem(81, new ItemStack(resultItem.split(" ")[0], Number(resultItem.split(" ")[1])));
simple arch
# warm mason Yes, like gpt.

Well if I'm going to be using gpt I have to use a bedrock dedicated server.. which idk how I can start making it and even setting it up.

dim tusk
elfin rose
#

ok

strange marsh
#

I thought I'd forward this here for those that are curious about V2's upcoming changes that (I don't think?) have been publicized.

uncut mason
#

Is it possible to programmatically apply an item to an item frame via script api?

granite cape
tight plume
#

why are you making poop

#

or chair

floral vessel
#

is there a way to duplicate an entity?

#

oh wait

#

do scripts even work on falling snow?

drowsy scaffold
#

how do I set the player's view direction? I know there's an accessor method I just wasn't sure if there was a mutator method I wasn't aware of

dim tusk
#

I want a breed component

dim tusk
#

C'mon guys don't be weird...

#

We have a tameable components accessible in scripts, how about breeding?

dusky pulsar
#

I like hamburgers

dim tusk
thorn flicker
#

||idk||

dim tusk
#

No. I'm gonna throw a tantrums here.

thorn flicker
dim tusk
thorn flicker
#

im aware

dim tusk
dim tusk
valid ice
dim tusk
shell sigil
#

Guys what is target? I see it in entity class here example
world.afterEvents.playerSpawn.subscribe(player=>console.warn(player.target)) what is this do can you give example?

warm mason
shell sigil
#

Awhhhh thx I understand now

dim tusk
#

Umm, just a confirmation... I want to sort something into alphabetical order, but the words are translated is it possible to do that?

slow walrus
dim tusk
slow walrus
#

then no

#

you can't get the translated version of the key in scripts afaik

quick shoal
#

Guys is there anyway to export the world in minecraft pe with ORE UI? I'm stuck for it

distant tulip
#

just get the world from files

quick shoal
distant tulip
#

zip it and change file type

quick shoal
#

must from the export method

distant tulip
#

there is no different

quick shoal
#

Alr

dim tusk
#

How many lines of strings do you guys think the body in the server form can handle before it lags your devices?

subtle cove
elder heath
#

Can you create a poster with custom text using js?

dim tusk
coral ermine
#
const response = form.show(player);
    system.runTimeout(() => {
       if (time > 0 && !response.canceled) {
         uiManager.closeAllForms(player);
         waitUntilOpens(player);
       } else if (time === 0) {
         uiManager.closeAllForms(player);
       }
   }, 20);

Why form keeps opening even I’m closing it?

#

?

subtle cove
#

Also

const response = form.show(player);
    system.runTimeout(() => {
       if (time > 0 && response.cancelationReason ===  "UserBusy") {
         uiManager.closeAllForms(player);
         waitUntilOpens(player);
       } else if (time <= 0) {
         uiManager.closeAllForms(player);
       }
   }, 20);
coral ermine
#

I need to make it keep updating until player closes the form

#

but it keeps opening when player closes form

fading sand
#

Im trying json ui again, can anyone tell me why the ui form wont show?:

world.afterEvents.playerSpawn.subscribe(({
    player, initialSpawn
}) => {
    if (initialSpawn) {
        console.warn("JOINNNNNNNN");

        const players = world.getPlayers();
        const modalForm = new ModalFormData().title("Example Modal Controls for §o§7ModalFormData§r");

        modalForm.textField("Input w/o default", "type text here");
        modalForm.textField("Input w/ default", "type text here", "this is default");

        modalForm.show(players[0]).then((formData) => {
            players[0].sendMessage(`Modal form results: ${JSON.stringify(formData.formValues, undefined, 2)}`);
        })

    }
});```
shadow geyser
#

hey uh how do i fetch player's tag?

warm mason
shadow geyser
#

ah thanks

coral ermine
warm mason
#
function updateUntilClose(player) {
  let menu = new ActionFormData()
  /*
    Form settings
  */
  let close = false
  menu.show(player).then(data => {
    if (data.canceled) close = true
  })

  system.runTimeout(() => {
    if (close) return
    UIManager.closeAllForms(player);
    updateUntilClose(player)
  },3)
}
fading sand
#
function myForm(player) {
  let menu = new ModalFormData().title("Example form")
  menu.textField("Input w/o default", "type text here");
  menu.show(player).then(data => {

    if (data.cancelationReason == "UserBusy") {
      
      return system.runTimeout(() => {
        myForm(player)
      }, 10)
    }
    //Code if the form was shown
    console.warn(formData.formValues);
  })
}```
For some reason the form value is invalid
warm mason
fading sand
warm mason
fading sand
#

OH

#

Lmao thx

jolly citrus
#
world.beforeEvents.playerBreakBlock.subscribe((event) => {
    Object.entries(Enchantments).forEach(([key, value]) => {
        if (value.onEvent === event.constructor) {
            if (!(event.itemStack && ItemUtils.getItemType(event.itemStack).length > 0)) return;

            const Enchant = EnchantmentUtils.getEnchantments(event.itemStack).find(enchantment => enchantment.name === key);
            
            if (Enchant) {
                value.Callback(event, Enchant);
            }
        }
    })
})

can somebody explain to me why indexing anything on event after the if (value.onEvent === event.constructor) condition defines the type of event to be never ?

value.onEvent: typeof PlayerBreakBlockBeforeEvent | typeof ArmorIterationEvent | typeof CustomHitEvent

#

this condition worked just fine for me when i used jS

#

I understand that it's comparing an Event class to a function but ehh it's confusing me a bit, the condition works in terms of logic but it gives errors in ts

sharp elbow
#

Are you intending to see if value is an instance of event? Because you can use if(value.onEvent instanceof event)

jolly citrus
#

nvm

#

switched it to event.constructor and it works

#

thx

fading sand
#

How do i change an join message?

#

And how can i change an player name?

jolly citrus
jolly citrus
fading sand
fading sand
warm mason
jolly citrus
fading sand
#

Ahh

jolly citrus
#

if you get a player from an event it's an instance created from the Player class, these objects have a nameTag property

fading sand
jolly citrus
fading sand
#

?

jolly citrus
#

from what I know only the player name displayed on the use of /w & 3d name tags in game

fading sand
#

Sheet

jolly citrus
#

the name property is what's used for kill messages and such but it's read-only

jolly citrus
fading sand
#

Oh rip

fading sand
jolly citrus
#

that's what you'd use it for

fading sand
#

Or can we replace player name with nameTaf

jolly citrus
#

the name and nameTag properties are two different things

jolly citrus
#

%s represents the name of the player

#

but afaik you cant rlly update that

fading sand
jolly citrus
#

ask in #1067869318383157430 or #1067869590400544869 i think

fading sand
jolly citrus
#

create a fake leave/join msg using scripts

#

and make the vanilla message display as empty

#

it will create a new line in chat yes but it's just a visual issue

fading sand
#

🤔alr

jolly citrus
#

i can make a helper class for you

#

im assuming you want to make a nicking system?

#

so players can disguise themselves better

#

a fake name

fading sand
#

O: thats be great ig, yea, like to stay anonymous

jolly citrus
#

TypeScript:

class NickUtils {
    getPlayerName (player: Player) {
        return player.getDynamicProperty("nick") ?? player.name;
    }

    updateNick (player: Player, nick: string) {
        player.setDynamicProperty("nick", nick);
    }

    resetNick (player: Player) {
        player.setDynamicProperty("nick", undefined);
    }
}
class NickUtils {
    getPlayerName (player) {
        return player.getDynamicProperty("nick") ?? player.name;
    }

    updateNick (player, nick) {
        player.setDynamicProperty("nick", nick);
    }

    resetNick (player) {
        player.setDynamicProperty("nick", undefined);
    }
}
#

wait

#

lemme add 1 mroe

#

use NickUtils.getPlayerName(player) anywhere to get their name; it always prioritizes retrieving their nickname over their actual username, bc name is always defined, the nick property is not

#

if you want to remove their nickname use NickUtils.resetNick(player)

#

if you want to update their nickname use NickUtils.updateNick(player, nick)

#

const nickCommand = "!nick %s";
const resetNickParameter = "reset";

world.beforeEvents.chatSend.subscribe((event) => {
    const { sender, message } = event;
    if (message.startsWith(nickCommand.split(" ")[0])) {
        const nick = message.replace(/@/g,'').match(/"[^"]+"|\S+/g)?.[1].replace(/"/g,'');
        if (nick) {
            nick !== resetNickParameter ? NickUtils.updateNick(sender, nick) : NickUtils.resetNick(sender)
        }
    }
})
#

example usage

#

wait

fading sand
#
world.afterEvents.playerSpawn.subscribe(({
    player, initialSpawn
}) => {
    if (initialSpawn) {
        myForm(player);

    }
});



let playerName = new Map();


function myForm(player) {
    let menu = new ModalFormData().title("Example form")
    menu.textField("Input w/o default",
        "type text here");
    menu.show(player).then(data => {

        if (data.cancelationReason == "UserBusy") {

            return system.runTimeout(() => {
                myForm(player)
            }, 10)
        }
        playerName.set(player, data.formValues);
        player.nameTag = data.formValues;
    })
}




world.beforeEvents.chatSend.subscribe(data => {
    const senderEntity = data.sender;
    let senderName = playerName.get(senderEntity);
    const message = data.message;
    world.sendMessage(` ${senderName}${message}`);
    data.cancel = true;
})```
jolly citrus
fading sand
#

Works just for chat rn

jolly citrus
#

but do note that maps reset when a player leaves

#

if you want that then it's ok

chilly fractal
#

My guys why yall over complicating the task?

jolly citrus
#

i mean

#

when the scripts are reloaded**

fading sand
#

Missing is:
Join/leave message
Death and kill messafe

fading sand
jolly citrus
#

so that's why I recommend a dynamic property

fading sand
#

Alr yea, property is better than

chilly fractal
#

A whole utility for a nick?

#

And sending custom messages.

jolly citrus
jolly citrus
chilly fractal
#

But sure, yall do whatever yall wanna do.. I am busy rn so I can't really show you want I mean.

chilly fractal
jolly citrus
chilly fractal
#

Sure just you do you

jolly citrus
#

i think it's a good practice to use classes or whatever

fading sand
#

Ima be back in some hours prob

jolly citrus
#

maybe this isn't a good scale to represent the benefits of it

chilly fractal
chilly fractal
#

Yeah.

jolly citrus
#

but it still does keep it easier to maintain

jolly citrus
#

twice is already enough

#

to make a function for it

#

imo

#

once yeah maybe not

chilly fractal
#

Bruh

jolly citrus
#

and there might be other ways that he wants the players to be able to change their nickname

#

than just a chat command

chilly fractal
#

I'm sorry for starting this argument just go on bruh, you do you.

jolly citrus
#

no worries

chilly fractal
jolly citrus
subtle cove
#

-# hence where code...

jolly citrus
#
    static enchant (itemStack: ItemStack, enchantment: Enchantment): ItemStack {
        const properties = {
            enchantmentSlots: itemStack.getDynamicProperty("enchantmentSlots") as number,
            usedEnchantmentSlots: itemStack.getDynamicProperty("usedEnchantmentSlots") as number,
            enchantments: JSON.parse(itemStack.getDynamicProperty("enchantments") as string) as Enchantment[] | string,
            whitescrolled: itemStack.getDynamicProperty("whitescrolled") as boolean,
            nameTag: itemStack.getDynamicProperty("nameTag") as string
        }

        if (!(Array.isArray(properties.enchantments))) return itemStack;

        if (properties.usedEnchantmentSlots >= properties.enchantmentSlots) return itemStack;

        const enchantmentExists = properties.enchantments.find(_enchantment => _enchantment.name === enchantment.name)

        if (enchantmentExists) {
            enchantmentExists.level = Math.min(Math.max(enchantmentExists.level+(enchantment.level-(enchantmentExists.level-1)), enchantment.level),(this.getEnchantment(enchantment.name) as typeof Enchantments[keyof typeof Enchantments]).MaxLevel)
        } else {
            properties.enchantments.push({
                name: enchantment.name,
                level: enchantment.level
            })
        }

        properties.usedEnchantmentSlots = (properties.enchantments).length

        properties.enchantments = JSON.stringify(properties.enchantments) as string;

        for (const [key, value] of Object.entries(properties)) {
            itemStack.setDynamicProperty(key, value);
        }

        const updatedItem = ItemUtils.updateLore(itemStack)
        if (updatedItem instanceof ItemStack) {
            return updatedItem;
        }

        return itemStack;
    }

i expected using as string statement when updating the value of properties.enchantments to force the type to now be string and not Enchantment[] | string, so now I get a type error here:

        /* for (const [key, value] of Object.entries(properties)) { */
            itemStack.setDynamicProperty(key, >> value <<);
        /* } */

how do i fix this

#

i tried a typeof type guard for it before I update dynamic properties but it doesn't change anything

proud saddle
#

if i return function with using system.run it garant what function will be completed in no more than a tick?

wheat condor
#

If someone is interested #1320052540582264912 message

simple arch
#

Wait @warm mason isn't there a
thing in github that uses gpt 💀 (idk felt like adding the skull)

#

For simulated players

simple arch
#

Codex

warm mason
#

????????????

celest relic
#

Does anybody know how much system.runInterval impacts server lag?

#

Is it a high or low impact?

simple arch
warm mason
warm mason
simple arch
#

Simulated Players using chatgpt look at the full codes, etc ...

thorn flicker
#

🤖

dim tusk
#

All I want for Christmas is a breed component

warm mason
distant tulip
simple arch
#

Yeah heard about hugging face tho?

distant tulip
#

the api is free?

thorn flicker
#

🤖

simple arch
#

Yes hugging face you just create an account and u get free API keys

#

Without paying a dime

#

U also have to find a model doe

thorn flicker
#

lol

dim tusk
thorn flicker
#

coddy, its time to move on

dim tusk
warm mason
#

Just make your own breed component

thorn flicker
#

you might be asking about it for years

dim tusk
warm mason
dim tusk
simple arch
dim tusk
thorn flicker
#

also I didnt say you were doing it for years, I said you will be, because thats how long it'll take to come out

dim tusk
#

Ahh, I get it...

#

Anyways unrelated but it took me 10 minutes to set up a lang file because i didn't read the docs properly on how to use %s, %%s and %%1...

thorn flicker
#

breed apis = 5 years

lore limit increase = 10 years

biome apis = 50 years

distant tulip
#

breed component, translation string sorting... what are you cooking?

dim tusk
dim tusk
warm mason
thorn flicker
dim tusk
thorn flicker
warm mason
#

Equippable for all entities - 1/0 years

thorn flicker
#

thats 15 years

#

dw

dim tusk
thorn flicker
wheat condor
#

Rotate players camera: not happened in any parallel universe

simple arch
#

I got equippable to work on simulated players

thorn flicker
#

what if the whole script api gets restarted

distant tulip
dim tusk
thorn flicker
#

lmao

#

coddy what happened to your pfp

dim tusk
warm mason
thorn flicker
dim tusk
#

I want something that is kinda describing me but somewhat cool...

wheat condor
#

In 2050 we will play Minecraft with ai friends 😭😭

dim tusk
#

But I don't know how to design that's why I left I blank

dim tusk
warm mason
thorn flicker
#

lmaooo

wheat condor
thorn flicker
#

I know nothing about you so I cant help you with that

#

a rat just came to mind

#

🐀

dim tusk
#

y'know what's funny, it's kinda reference in how I am kinda obsessed with the user that has a rat character....

wheat condor
dim tusk
#

I'm talking about Ignis

thorn flicker
#

"obsessed with use that is a rat here"

#

what does that mean

dim tusk
#

Username sorry

thorn flicker
#

oh.

dim tusk
#

God damnit, my auto correct is slipping

wheat condor
#

I understood the nonsense 👍

dim tusk
#

I asked this and nobody responded... What do you guys think the limit of lines of strings that the body of the server form can handle before it starts to slow down the game

warm mason
dim tusk
vast comet
#

long string in ui freeze the client for a bit

distant tulip
wheat condor
warm mason
#

800 is not much

distant tulip
wheat condor
#

Well some people define a 4060 as a potato

distant tulip
thorn flicker
distant tulip
wheat condor
# thorn flicker *what*

Long ago I asked in BuildAPc discord group and they said that a 3060 was trash, and they also recommended me a 400€ keyboard satin that it was the minumum

wheat condor
#

Was an example becouse now it the latest, when I was buying my pc I asked for 3060

warm mason
dim tusk
thorn flicker
#

😔

vast comet
#

afslut 🗿

dim tusk
#

I just realized that Game is paused isn't translated

thorn flicker
#

"markedsplads"

wheat condor
#

Is that flag from Czech Republic?

dim tusk
wheat condor
#

Ye

vast comet
#

lol

warm mason
#

I can't imagine how this reads

dim tusk
#

It's Philippine flag

thorn flicker
#

this is czech

wheat condor
#

Ohh

thorn flicker
wheat condor
thorn flicker
#

ohhh

wheat condor
#

You can’t be serious

dim tusk
#

Ohh no void...

thorn flicker
#

👍 👍

thorn flicker
#

you guys cant take a joke

wheat condor
#

You re Russian

dim tusk
wheat condor
#

What’s that alien language

warm mason
dim tusk
#

Russian spy... insert tf2 sound effects

distant tulip
#

bruh

thorn flicker
#

serty is russian yeah

warm mason
#

Oh no, I've been found out

autumn seal
#

t pose in 2024 is unexpected

wheat condor
dim tusk
warm mason
wheat condor
#

How do you manage to undersand this

thorn flicker
#

this is very script api related fellows

wheat condor
#

Yeah

dim tusk
#

This is starting to be like #art-and-modeling

wheat condor
#

Well if you want to talk about script api why don’t you take a look at this #1320052540582264912 message

valid ice
#

KEEP IT SCRIPT API GUYS FOR THE LOVE OF GOD

wheat condor
dim tusk
thorn flicker
#

hahaha

distant tulip
#

alr
-# bruh my joke got nuked

wheat condor
#

What joke

dim tusk
thorn flicker
#

minato you are still here, so the joke is not gone.

autumn seal
#

lmao

distant tulip
dim tusk
thorn flicker
#

im kidddinggg, 1 joke bullet for everyone

#

coddy, now you

dim tusk
wheat condor
autumn seal
dim tusk
#

Anyways, I just want BREED COMPONENT to be accessible...

thorn flicker
dim tusk
#

Yes I said it thrice already

wheat condor
#

I need that oreUi

warm mason
#

-# The moderator is already choosing a target

dim tusk
#

And if I lose my mind here, I will literally redo the whole breed system in scripts

dim tusk
autumn seal
#

Is it denial to refuse to learn json ui until oreui comes out?

dim tusk
valid ice
autumn seal
#

It'll pay off in 5 or so years

distant tulip
wheat condor
thorn flicker
dim tusk
#

Your just blind

thorn flicker
#

"Your exist blind"

autumn seal
#

being able to read something ≠ it being easy to read

thorn flicker
#

"Your hust blind "

distant tulip
#

used to hate it, now i kinda like it

thorn flicker
#

"Your just blind "

#

you're*

wheat condor
#

3 years 😭😭 1 year ago I didn’t even know that I could make Minecraft addon by myself

dim tusk
#

FOR UFCK SAKE AUTO CORRECT 💯

thorn flicker
#

lmaooo

thorn flicker
#

its okay

#

calm down

dim tusk
#

Now I'm losing my mind not because of scripts but because of auto correct!!!

dim tusk
wheat condor
#

Yeah iOS 18 is a$$

valid ice
#

#off-topic

autumn seal
#

Instead of a mob vote they should host a vote on adding features to the bedrock development community

dim tusk
#

This is becoming off topic

thorn flicker
wheat condor
#

Just rename the channel to “off topic”

#

Is not that hard

thorn flicker
#

I thought iphones were related to minecraft

dim tusk
#

Pls 🥺🙏

valid ice
thorn flicker
#

im sensing an evil presence

#

you guys should listen

dim tusk
wheat condor
dim tusk
#

Let's move cause Herobrine will literally activate and one shot us all

dim tusk
autumn seal
#

is it off topic if you formatted every message
world.sendMessage("like this?")

dim tusk
#

Stop spamming gifs or images now

wheat condor
#

Is heroine here looking for gift to delete?

#

Herobrine

autumn seal
#

if only there was a channel that conversations with no topic could take place in 😔

dusky pulsar
#

Time to make herobrine64 mob

#

and he deletes your player data like a gif

#

where do you go to talk about jigsaw blocks

wheat condor
#

That’s script api related 👍👍👍🔥🔥🔥🔥🔥 #1320052540582264912 message

dusky pulsar
#

He's just a moneyman doing business

wheat condor
distant tulip
#

nah, he is trying to save the channel

wheat condor
wheat condor
dusky pulsar
#

On your actionbar thing?

#

-# I don't really use/care about action bars

dim tusk
#

🕳️

distant tulip
dusky pulsar
#

-# so I can't give a good opinion

autumn seal
#

The 20k jam submissions having no topic ironically makes it harder for me to come up with something for it

dusky pulsar
#

It should make it easier

#

anything you want

wheat condor
dusky pulsar
#

OH

#

The video

wheat condor
dusky pulsar
#

"I undastand it now"

wheat condor
#

4*

thorn flicker
wheat condor
#

Thanks

dusky pulsar
#

Can jigsaws be scripted

thorn flicker
dusky pulsar
#

sometimes these things can overlap if you start using turns and stuff for the path

#

and I'm allergic to structures overlapping 😷

wheat condor
#

I used to play on that thing

distant tulip
wheat condor
#

Did you know 1981 was the year of raaaahhhhhhhhhh 👏👏

distant tulip
#

structures would be a game changer if we could exclude/include entities using entity filter

thorn flicker
distant tulip
#

he can't if he is the joke

distant tulip
autumn seal
#

you can?

distant tulip
#

in structures?

wheat condor
distant tulip
#

yeah i am out of here
and they already do btw... who ever tf was that

wheat condor
#

Just use the command

wheat condor
#

! true (script api related)

warm mason
dusky pulsar
#

don't java villages have some type of anti collision logic with their jigsaws when generating

autumn seal
#

the audit logs would reflect differently

dusky pulsar
#

-# If I get a good idea of what that is I could probably script it

distant tulip
wheat condor
wary edge
#

Where scripting?

wheat condor
dusky pulsar
warm mason
#

Why do you need jigsaw when there are scripts? :)

dusky pulsar
#

village generator worked up until I added turns on the path then they started going in on themselves

dusky pulsar
wheat condor
# dusky pulsar I thought it was easy

It’s the most complex thing in the world, they don’t have auto completions they have old ui and code lines like command blocks that don’t have auto completions

dusky pulsar
#

testing it out was fun

dusky pulsar
vast comet
#

scripting is the friend we made along the way

wheat condor
#

That is what a jigsaw looks like

dusky pulsar
wary edge
#

Please move elsewhere.

dusky pulsar
#

I'm here for a reason

autumn seal
#

what do you guys think would be the best way to add a custom effect/potion effect

#

I don't imagine there's any support for that so would giving the entity a tag and running something every tick be one way to go?

autumn seal
#

that's unfortunate

drowsy scaffold
#

how do I make a simluated player?

abstract cave
#

Is there a player hit entity event?

valid ice
abstract cave
valid ice
#

Is a player not an entity?

#

They likely won't add a separate event solely for player, as the entity one does the job just fine and is a more general use case.

abstract cave
#

🫤

warm mason
#

What's the problem with just writing one if

abstract cave
#

i have, im just asking if theres a direct method of doing it

valid ice
#

There sure ain't

jolly citrus
#

can the gravity of knockback to players be modified

thorn flicker
#

an if statement is stressful?

dusky pulsar
#

don't think about it your brain will melt

thorn flicker
#

theirs or mine?

dusky pulsar
#

✅ all of the above

abstract cave
thorn flicker
#

has to be a troll.

abstract cave
#

😠

dusky pulsar
#

It doesn't get any easier than a single if statement 😭

thorn flicker
autumn seal
jolly citrus
#

or like

#

inertia

#

more of

#

i feel like the player falls back down too fast, it's hard to hit anybody high up in the air

#

trying to make custom knockback

autumn seal
#

Im not sure how to go about that

#

maybe use entity hit entity event, wait a second or less, grab player velocity and multiply it and apply to knockback ?

#

you can also likely just get direction between you and hit entity, and apply a flat amount of knockback in a certain direction

quick shoal
thorn flicker
# quick shoal U shouldn't ``player[0]`` just player

they need to first create a for of loop to do that (or use forEach)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

MDN Web Docs

The for...of statement executes a loop that operates on a sequence of values sourced from an iterable object. Iterable objects include instances of built-ins such as Array, String, TypedArray, Map, Set, NodeList (and other DOM collections), as well as the arguments object, generators produced by generator functions, and user-defined iterables.

dim tusk
#

Halo

#

what'd you guys think better to sue to add a comma in numbers like every 3 digit

thorn flicker
dim tusk
#

Use toLocaleString() or custom function

fading sand
jolly citrus
#

the vanilla kb speed is too quick

chilly fractal
#

.addEffect('slow_falling') r/wow

#

No no

#

It's too inefficient

jolly citrus
chilly fractal
#

.applyKnockback(); // test and find out the perfect knockback value for applying knockback from the bottom

quick shoal
jolly citrus
#

the kb itself works but the values just are not good for actual pvp

quick shoal
jolly citrus
quick shoal
#

Im alr looking for it for a long time

jolly citrus
#

there's more to my pvp system than just the knockback itself

jolly citrus
quick shoal
#

I can't make It perfectly

jolly citrus
#

well neither can I and that's why I'm here asking for help with it

quick shoal
#

I just need a low knockback and high falling

jolly citrus
quick shoal
jolly citrus
#

?

quick shoal
#

But the effect is not good

jolly citrus
#

i have the same problem Thumbs

#

its not fun to pvp with its awful even vanilla kb is better

quick shoal
jolly citrus
#

with the double hits

chilly fractal
#
.getVelocity();
// there is a post somewhere in this server that eventually leads to converting that value to kb
.applyKnockback();
// edit the kb to your liking :)
autumn seal
#

I said this

quick shoal
jolly citrus
quick shoal
#

This is what I do

chilly fractal
jolly citrus
chilly fractal
#

Unless you mean the attacking speed

jolly citrus
chilly fractal
#

It literally dismantles them.

jolly citrus
#

the speed that the knockback takes effect at

autumn seal
#

Making the player fall slower is likely going to require running a teleport every tick or giving them slow falling

quick shoal
jolly citrus
autumn seal
#

Increasing the height they go up is very easy and is a parameter of knockback as is

jolly citrus
#

i was wondering if there's a way to modify that

chilly fractal
#

Sigh, let me find the post for ya rq

quick shoal
#

I think I already have a nice value for applyknockback but the code is not perfect

jolly citrus
#

it seems fine to me

quick shoal
jolly citrus
chilly fractal
random flint
#

Is there a way to change the entity's name shown on a bossbar? Using .nameTag = doesn't update it.

random flint
#

yeah, using component grouo for the bossbar

#

am i not supposed to?

ruby haven
random flint
#

I want to change it dynamically using scripts

dim tusk
random flint
#

I found a janky workaround using runCommand() and /summon

sterile epoch
#

whats wrong with maxDistance in getEntities

#

nevermind im just slow af

runic crypt
#

Can anyone help me make a anti combat log system ??

#

If anyone can then please ping me

turbid delta
#

are these bad stats

warm mason
turbid delta
dim tusk
#

Why fetch them? Are they important?

warm mason
round bone
#

but there's not really any really useful case that you can use them in practise

turbid delta
#

Felt like they wouldve been valuable to help me visualize if my scripts were efficient or needed work

round bone
round bone
#

or just benchmark it

dim tusk
#

They won't really help you check it..m

turbid delta
# warm mason Use a TPS counter

tps is 20 up until like 30 players and i cant even tell if its my scripts anymore cause of how much times ive refactored it always seem to lag just as much

turbid delta
#

im only using 1% of my total ram and 2% of my total cpu

#

I'd love to be able to handle more players but doesn't seem like something I can do

#

Not sure whats the cause

round bone
#

if it'll be some public add-on I wouldn't care about performance on bigger numbers

round bone
#

as far as it's okay for 10-15 players it's good

turbid delta
#

I'm using my own addon for a network 😅

round bone
#

oh, then this might be a small issue if you have more than 30 players

turbid delta
#

Anyone know if its a good idea to run 10000+ world.structureManager.load() at once to replace setType() 💀 or fillBlocks()

round bone
turbid delta
#

Probably could just thinking about making a simple world edit and since setType doesn't work in unloaded chunks it'd be nice to work at a larger scale which structures provide

#

I could definitely split it up

shut citrus
#

J

#

J

tiny tartan
#

if i do player.__leftClick = true
can i get that value in different event even if that event will be in different file?

turbid delta
#

Player seems to save its properties across events and what not, its pretty damn useful

runic crypt
#

How to I make a anti combat log system ?
Can anyone help me or hive me advice?

turbid delta
#

beforePlayerLeave event, save all the items into an array, and then in the next tick spawn the items

chilly fractal
#

Enough advise there to get you fairly 70% of the way there.

runic crypt
#

yep just saw tysm 🙂

chilly fractal
#

You're welcome.

autumn seal
#

What's the best method of spawning something only certain players can see, is there any way to make a particle or something else that is only visible to certain players?

autumn seal
#

Thanks

wheat condor
#

block.setPermutation('perm','value')
whats the correct syntax???

warm mason
wheat condor
# warm mason ```js import { BlockPermutation } from '@minecraft/server' block.setPermutation...
if (itemStack?.typeId !== 'worldedit:debugstick') return;
    const states = block.permutation.getAllStates()
    const kv = []
    Object.entries(states).forEach(([key, value]) => {
        kv.push([key + ':' + value])
    });
    new ActionbarMenu()
        .title('BlockStates')
        .pattern(kv)
        .show(player).then(({ slot, line }) => {
            /**@type {string} */
            const result = kv[line][slot].split(':')
            const perm = BlockPermutation.resolve(block.type, { result[0]: parseInt(result[1]) + 1 });

            block.setPermutationperm)
        })

im trying to create a debug stick

#

is that right?

warm mason
#
BlockPermutation.resolve(block.type, { [result[0]]: parseInt(result[1])+1 });
wheat condor
wheat condor
# warm mason ```js BlockPermutation.resolve(block.type, { [result[0]]: parseInt(result[1])+1 ...
world.afterEvents.itemUseOn.subscribe(({ source: player, itemStack, block }) => {
    if (itemStack?.typeId !== 'worldedit:debugstick') return;
    const states = block.permutation.getAllStates()
    const kv = []
    Object.entries(states).forEach(([key, value]) => {
        kv.push([key + ':' + value])
    });
    new ActionbarMenu()
        .title('BlockStates')
        .pattern(kv)
        .show(player).then(({ slot, line }) => {
            const result = kv[line][slot].split(':')
            console.log(result[0])
            const permId = result[0]
            // the next line does throw
            const perm = BlockPermutation.resolve(block.type, { [permId]: true });

            block.setPermutation(perm)
        })
})
#

permId isnt working why?

#

found out that arg[0] is block type not permId so the error was that i needed to use typeId instead of type

cold grove
wheat condor
#

yes but i was thinking the arg[0] was the permId

grim raft
#

it is not reading the ${slot}

system.runInterval(() => {
    for (const player of world.getPlayers()) {
        let slot = player.selectedSlot;
        player.runCommand(`scoreboard players set @s hotbar ${slot}`);
    }
});```
chilly fractal
grim raft
chilly fractal
#

That script is quite outdated righ? (Cuz that change has been in the api for maybe like 3 updates or more)

grim raft
#

idk

#

I think im outdated

drowsy scaffold
#

what is the playsound for tnt exploding? I can't get it to work

distant tulip
#

random.explode
random.fuse

drowsy scaffold
#

ah that would be it

#

thank you

low mica
#

anyone know how i can format something to look like this?

#
.body(`§bWelcome §e${player.name}, §bYou have §2$§a${money}§b. §3Please select an option from down below!`)

i would also like it to be put in this

gaunt salmonBOT
patent tapir
#
import { world } from "@minecraft/server"

world.beforeEvents.playerPlaceBlock.subscribe((eventData) => {
  const blockGP = eventData.permutationBeingPlaced.type.id
  const blockBPO = eventData.block
  if (blockGP === "minecraft:soul_torch" && !blockBPO.matches("bedrock")) {
    eventData.cancel = true
  } else if (blockGP === "minecraft:soul_torch" && blockBPO.matches("bedrock")) {
    world.sendMessage({
      rawtext:
        [
          {
            text: `§5§o${playerName} has placed a torch`
          }
        ]
    })
  }
}) ```
Why can’t I place the soul torch ANYWHERE?
patent tapir
thorn flicker
#

well wait, thats what the code does though, to cancel...

#

if its not bedrock, itll cancel

patent tapir
#

yes

#

i only want it placed on bedrock

thorn flicker
#

are you are asking why you cant place it anywhere...

patent tapir
thorn flicker
#

weird wording.

patent tapir
#

I’ll try adding the namespace and I’ll be damned if somehow that works

#

Still doesn’t work

#

Torch does not get placed and no message is sent

#

Although i did forget to add a system.run so I’ll do that but still

thorn flicker
patent tapir
#

Wait really

#

Ohmg

thorn flicker
#

you cannot check what its being placed on

patent tapir
#

I mixed up the variables :(

patent tapir
thorn flicker
#

use beforeEvents interact with block

patent tapir
#

Then what’s with “blockpermutationbeingplacedon”

thorn flicker
#

then cancel that

thorn flicker
#

not "permutationBeingPlacedOn"

patent tapir
#

Wow I’m incredibly dumb

thorn flicker
#

misread 🤷‍♂️

thorn flicker
celest abyss
#

There is a way to detect when a player mounts an entity?

dawn zealot
low mica
cold grove
celest abyss
celest abyss
#

Ty

dense inlet
#

Is there a way to save any kind of data. Like if I want to save a string of data for when the world is closed or a server stops running?

cold grove
dense inlet
#

thanks!

slow walrus
#

om my gosh guys!!!! I was message number 100k !!!!

tidal wasp
#

Cam you register multiple components with the same world.before.events?

dusky pulsar
tight plume
#

AYO IM THE MESSAGE 100K

sage portal
#

[Everyone](#1067535608660107284 message) has [been](#1067535608660107284 message) message [100K,](
#1067535608660107284 message), it's [not](#1067535608660107284 message) really [that](#1067535608660107284 message) special [to](#1067535608660107284 message) get [anymore](#1067535608660107284 message) .

obsidian coyote
#

Now it's like over 200k messages pfft

#

I need to check later

fast wind
#

I have a "system.runInterval()" that every 2 seconds gives an effect to all players using "for (let player of world.getAllPlayers()) {}" but for some reason it only targets one player, I do have other things that run inside the "for".

wheat condor
fast wind
#

Thanks

dense inlet
#

Anyone know of the world.beforeEvents.chatSend event is currently working? I get an error saying that it is undefined when I try to use it.

dense inlet
#

I do have beta apis turned on in the world though, so idk

fallen cape
lilac glacier
#

can anyone tell me what's the right number for the y part in my apply knockback script if I wanted my mob's jumping range to be far as 24 - 27 blocks?

#

system.afterEvents.scriptEventReceive.subscribe((event) => {
  const source = event.sourceEntity
  const target = source.target;
  const dimension = world.getDimension("overworld");
  try {
    switch (event.id) {
      case "cod:event_knockback":
        if (target !== undefined) {
          source.applyKnockback(source.getViewDirection().x, source.getViewDirection().z, 9, 0.5);```
somber cedar
hushed ravine
#

Is it a good idea to have an instance for each player to run parallel tasks instead of just doing a for loop? This is an example of one

export class PlayerInstance {

  private static players: PlayerInstance[] = [];

  private readonly entity: Player;
  private readonly routine: number;

  constructor(entity: Player) {
    this.entity = entity;
    this.routine = system.runInterval(() => this.update(), 1);
  }

  private update(): void {
    this.entity.onScreenDisplay.setActionBar(`§6Sneaking: §c${this.entity.isSneaking}§6 | §eSwimming: §c${this.entity.isSwimming}§6`);
  }

  public close(): void {
    system.clearRun(this.routine);
  }

  public static getPlayer(entity: Player): PlayerInstance | undefined {
    return this.players.find(player => player.entity === entity);
  }

  public static getPlayers(): PlayerInstance[] {
    return this.players;
  }

}
distant gulch
#

I think yes,because then you got a better control for each player

warm mason
nimble schooner
#

What did they change to this? 😭

let component = itemFormatted.getComponent("minecraft:enchantable");
            component.addEnchantment({ type: new EnchantmentType(`${enchant.type}`), level: enchant.level })```
#

Apparently itemStack.getComponent(„minecraft:enchantable“) returns undefined

warm mason
amber granite
#

Hillo

nimble schooner
warm mason
#

Yeah, but why put that on a string instead of just writing enchant.type

nimble schooner
#

Idk

#

Wrote that one year ago

sterile epoch
#

does the player leave before event work now?

hushed ravine
hushed ravine
#
  private update(): void {
    if (world.getPlayers({ name: this.name }).length === 0) {
      this.close();
      return;
    }

    this.entity.onScreenDisplay.setActionBar(`§6Sneaking: §c${this.entity.isSneaking}§6 | §eSwimming: §c${this.entity.isSwimming}§6`);
  }

  public close(): void {
    system.clearRun(this.routine);
    const index = PlayerInstance.players.indexOf(this);
    if (index !== -1) {
      PlayerInstance.players.splice(index, 1);
    }
  }

Is there any other way that I can check if the player left the server? I feel like the method I used might use more resources

warm mason
#
if (player.isValid())
hushed ravine
#

How did I not know about this

warm mason
#

Why not just use a loop in system.runInterval that loops through all players

hushed ravine
#

So I'm trying to run things in parallel instead

granite badger
warm mason
hushed ravine
#

Especially with BDS

sterile epoch
# quick shoal Why it doesn't work

this isnt working:

world.beforeEvents.playerLeave.subscribe(({player}) => {
    const item = player.getComponent("inventory")?.container?.getItem(player.selectedSlotIndex);
    system.run(() => {
    player.dimension.spawnItem(item, {
        x: player.location.x,
        y: player.location.y,
        z: player.location.z + 5
    })
})
})
#

its not spawning the item

wary edge
sterile epoch
#

yes

#

does it only work on non-host players?

#

bruh

#

I just realised I made a spelling mistake

warm mason
sterile epoch
#

I forgot to use system and it said "does not have privileges" error, so that means it does run

warm mason
#

Yes, because this is before player has left, and after that if you use system.run nothing will work. Because there is no host

sterile epoch
#

oh