#Script API General

1 messages · Page 51 of 1

warm mason
#

You can detect explosions using this event. Other types of block breaking cannot be detected

#

If the documentation contains an example for TS, this does not mean that it is only available for TS

dawn zealot
warm mason
wary edge
#

Please elaborate.

dawn zealot
warm mason
dawn zealot
#

i just want my item name from the item when its dropped

wary edge
#

Then use this @dawn zealot

dawn zealot
#

then i got linked something i read it but its ts then im getting redirected ti so many different links

somber cedar
#
    world.getDimension('overworld').getEntities().forEach((entity) => {
    if (entity.typeId !== "minecraft:item") return;
    const item = entity.getComponent("item");
    if (item.itemStack.typeId == 'your:item') {
    };
    })
dawn zealot
wary edge
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/

stark kestrel
stark kestrel
#

ty

dawn zealot
warm mason
dawn zealot
#
    world.getDimension('overworld').getEntities().forEach((entity) => {
            const item = entity.getComponent("item");
                if (item.itemStack.typeId == 'power:damage_reduction1') {
                    console.warn("hi")
        };
    })
subtle cove
#

mhmmmmmm

somber cedar
#

if (entity.typeId !== "minecraft:item") return;

warm mason
#
   world.getDimension('overworld').getEntities({type: 'item'}).forEach((entity) => {
            const item = entity.getComponent("item");
                if (item.itemStack.typeId == 'power:damage_reduction1') {
                    console.warn("hi")
        };
    })
dawn zealot
#

works 👍 think i understand it now

solar dagger
#

Yeah I would look at the docs if I were you

vital halo
#

Is there a way to make fog appear only in certain world heights?

cold grove
#

with commands, idk if in the latest beta they added fog features

past blaze
#

Is there a difference between moveItem and transferItem?

cold grove
#
moveItem(fromSlot: number, toSlot: number, toContainer: Container): void
transferItem(fromSlot: number, toContainer: Container): ItemStack | undefined
past blaze
#

Why does transferItem only need to specify one slot?

cold grove
wary edge
#

Transfer is probably just, try to transfer, it may or may not fail?

cold grove
past blaze
#

Yet it takes two slots

cold grove
#

ah sorry

cold grove
past blaze
jolly veldt
#

Is setCurrentValue still a function?

#

I'm trying to modify minecraft:variant through script and it claims it is no longer a function

stark kestrel
#
world.afterEvents.playerSpawn.subscribe((data) => {
  const player = data.player;
  let level = player.getDynamicProperty("level")
  let rank =
    player.getTags()
      .find((tag) => tag.startsWith("rank:"))
      ?.split(":")[1];
  if (!rank) {
    let rank = '§8Cosmonaut'
    player.nameTag = `${rank}\n§b${level}§r ${player.name}`
  }
});``` any idea why this doesnt work?
#

it has no errors

jolly veldt
cold grove
#

do you have any tags on you?

stark kestrel
covert goblet
#

is there any advantage to storing dynamic properties on the player instead of the world?? other than the properties being avaialble even if the player is offline??

chilly fractal
#

Except of course, having the dp on each player instead of an array of players with their values (why would you even do this?, just put it on each player frfr)

covert goblet
#

i thought as much, ive got a set of universal "quests" and "stats" and i had each of the players progress stored on the world DP!! figured it would best to record it on each player, just wanted to check my logic

jolly veldt
#

1 hour later

#

Still no progress cuz idk where the problem is😭

crude bridge
#

id of the cow*

world.afterEvents.entityHitEntity.subscribe(data => {
const {damagingEntity, hitEntity} = data;
switch (hitEntity.typeId) {
case 'cow': primaryMenu(player); break;
}
});

crude bridge
distant tulip
crude bridge
distant tulip
#

interactions with?

crude bridge
distant tulip
#

playerInteractWithEntity
afterEvents only work for entities with the itneract component
so use beforeEvents

jolly veldt
#
    let entityVariant = event.source.dimension.spawnEntity("dwellers:butterfly", event.source.location).getComponent("minecraft:variant")
    switch (event.itemStack.getLore()[0]) {
      case "Blue Butterfly":
        entityVariant.setCurrentValue(0)
        break
      case "Red Butterfly":
        entityVariant.setCurrentValue(1)
        break
      case "Green Butterfly":
        entityVariant.setCurrentValue(2)
        break
      case "Orange Butterfly":
        entityVariant.setCurrentValue(3)
        break
      case "Amber Butterfly":
        entityVariant.setCurrentValue(4)
        break
      case "Black Butterfly":
        entityVariant.setCurrentValue(5)
        break
    }
    event.source.getComponent("minecraft:inventory").container.setItem(event.source.selectedSlotIndex, itemStack)
#

Here is the code

valid ice
#

Context??

jolly veldt
#

The problem mentioned above

#

It outputs no errors

valid ice
#

Try entityVariant.value = something

jolly veldt
#

Tried that prior, is says it is read-only

cinder shadow
#

put it inside a system.run

warm mason
#

You cannot change variant using scripts

valid ice
#

or use entity properties

jolly veldt
twilit tartan
#
world.beforeEvents.playerBreakBlock.subscribe((ev) => {
    let player = ev.player;
    let block = ev.block;

    if (player && player.isValid() && player.typeId === 'minecraft:player') {
        const mainhand = player.getComponent('equippable').getEquipment('Mainhand');
        const itemId = mainhand?.typeId || '';
        if (itemId === 'cg:shovel_iron_lvl3') {
            system.run(() => {

                if (block.typeId === 'minecraft:sand' || block.typeId === 'minecraft:gravel') {
                    const entityPosition = block.location;
                    const startX = Math.floor(entityPosition.x) - 2;
                    const startY = Math.floor(entityPosition.y) - 2;
                    const startZ = Math.floor(entityPosition.z) - 2;

   
                    const nearbyEntities = player.dimension.getEntities({
                        location: {
                            x: startX + 2, 
                            y: startY + 2,
                            z: startZ + 2
                        },
                        radius: 5
                    });

                    
                    nearbyEntities.forEach(targetEntity => {
                        if (targetEntity.isValid() && targetEntity !== player) {
                           
                            if (targetEntity.hasComponent('health')) {
                                targetEntity.applyDamage(5);
                                targetEntity.setOnFire(5);
                                targetEntity.runCommandAsync(`particle cg:thunder_1 ${targetEntity.location.x} ${targetEntity.location.y} ${targetEntity.location.z}`);
                                targetEntity.runCommandAsync(`particle cg:thunder_2 ${targetEntity.location.x} ${targetEntity.location.y} ${targetEntity.location.z}`);
                                targetEntity.runCommandAsync(`playsound ambient.weather.thunder @a[r=10]`);
                            }
                        }
                    });
                }
            });
        }
    }
});```
#

For some reason, if I remove the block.type it works, but when I put it in it doesn't execute anything inside the same if, can someone help me?

#

forget i already solve xd

thorn flicker
warm mason
empty light
#

was thinking, is there like a best way to prevent someone from taking more kb for a slight amount of time after being hit?

warm mason
thorn flicker
#

I thought you meant in general

#

so in this case it wont be accurate ofc.

twilit tartan
twilit tartan
#
/////////////////////////////////////////////Shovel Iron

world.beforeEvents.playerBreakBlock.subscribe((ev) => {
    let player = ev.player;
    let block = ev.block;

    if (player && player.isValid() && player.typeId === 'minecraft:player') {
        const mainhand = player.getComponent('equippable').getEquipment('Mainhand');
        const itemId = mainhand?.typeId || '';
        if (block.typeId === 'minecraft:sand' || block.typeId === 'minecraft:gravel') {
            player.sendMessage(`block: ${block.typeId}`)
        if (itemId === 'cg:shovel_iron_lvl3') {
            system.run(() => {
                
                // Comprobar si el bloque es de arena o grava
                
                    const entityPosition = block.location;
                    const startX = Math.floor(entityPosition.x) - 2;
                    const startY = Math.floor(entityPosition.y) - 2;
                    const startZ = Math.floor(entityPosition.z) - 2;

                    // Obtener todas las entidades en el área de 5x5 alrededor del bloque roto
                    const nearbyEntities = player.dimension.getEntities({
                        location: {
                            x: startX + 2, // Centro del área
                            y: startY + 2,
                            z: startZ + 2
                        },
                        radius: 5
                    });

                    // Aplicar daño y efectos a las entidades cercanas, excepto al jugador
                    nearbyEntities.forEach(targetEntity => {
                        if (targetEntity.isValid() && targetEntity !== player) {
                            // Verificar si la entidad tiene componente de salud
                            if (targetEntity.hasComponent('health')) {
                                targetEntity.applyDamage(5);
                                targetEntity.setOnFire(5);
                                targetEntity.runCommandAsync(`particle cg:thunder_1 ${targetEntity.location.x} ${targetEntity.location.y} ${targetEntity.location.z}`);
                                targetEntity.runCommandAsync(`particle cg:thunder_2 ${targetEntity.location.x} ${targetEntity.location.y} ${targetEntity.location.z}`);
                                targetEntity.runCommandAsync(`playsound ambient.weather.thunder @a[r=10]`);
                            }
                        }
                    });
                
            });
        }
        }
    }
});```
empty light
#

i was thinking like maybe calculating their velocity after getting hi-

#

wh..

#

what the shit is that

#

thats a thang

twilit tartan
#

I just don't want that to be the player, and to check that they are mobs in the easiest way possible xD, I changed the order, I put the block check above the item check and that was what solved it

#

There is a lot more code apart from that xd, so don't worry, it's more than 5k lines, that was just a part

warm mason
twilit tartan
warm mason
twilit tartan
twilit tartan
# warm mason You think it works, but it doesn't.

When I break a block of those that are there, with the item that I pointed out, the particle should fall, setting the entity on fire, in a radius of 5 blocks around where the block was broken, and it does everything xd

warm mason
twilit tartan
#

There are things that are called differently, for example const entityPosition = block.location;, but I was just reusing some code I made a while ago

thorn flicker
twilit tartan
# warm mason Apparently you have enough other conditions. But that's the truth of JS - you ca...
////////////////////////////////////////////////////////////////Diamond Shovel

world.beforeEvents.playerBreakBlock.subscribe((ev) => {
    let player = ev.player;
    let block = ev.block;

    if (player && player.isValid() && player.typeId === 'minecraft:player') {
        if (
            block.typeId === 'minecraft:dirt' ||
            block.typeId === 'minecraft:gravel' ||
            block.typeId === 'minecraft:sand' || 
            block.typeId === 'minecraft:grass_block'
        ) {
            const mainhand = player.getComponent('equippable').getEquipment('Mainhand');
            const itemId = mainhand?.typeId || '';
            if (itemId === 'cg:shovel_diamond_lvl2') {
                let time = world.getTimeOfDay
                if(time >= 13500){
                    player.runCommandAsync(`give @s ${block.typeId} 1`)
                    player.runCommandAsync(`summon xp_orb`)
                }
            }
        }
    }})
#

why this dont works?

#

all works, but no in the if of the time

warm mason
#

getTimeOfDay is a function, you don't use it. (getTimeOfDay -> getTimeOfDay())

twilit tartan
jolly veldt
#
itemStack.setLore(itemStack.getLore().push([event.target.nameTag]))
#

Not sure why i get an error from this

slow walrus
crude bridge
#

how can i make a repair command

#

like u hold a sword and with the command it repair it

distant tulip
# crude bridge like u hold a sword and with the command it repair it
import { world } from "@minecraft/server"

world.beforeEvents.chatSend.subscribe((event) => {
    const player = event.sender
    if (event.message !== ";repair") return
    event.cancel = true
    const container = player.getComponent("inventory").container
    const heldItem = container.getItem(player.selectedSlotIndex)
    if (!heldItem) return player.sendMessage("§cyou are not holding any item")

    const durability = heldItem.getComponent("durability")
    if (!durability) return player.sendMessage("§cthe item you are holding cannot be repaired")

    durability.damage = 0
    container.setItem(player.selectedSlotIndex, heldItem)
    player.sendMessage("§ayour item has been repaired")
})

not tested

#

should work

crude bridge
#

Thx

vagrant flame
#

anybody used the durability with script API. i am having issues where it just says "fail to set damage" when called on a player tool during "afterEvents.playerBreakBlock"

#

basically all of the functions fail... i have tired printing the methods to make sure they are there. But to my knowledge after events is not readonly

wary edge
vagrant flame
#

I cant read the max durability

#

"failed to get property maxDurability. but if i print

for(var method in tool_durability){
  console.warn(method)
}```

maxdurability shows up.. If i print the component type id it shows up
#
[Scripting][warning]-typeId

[Scripting][warning]-getDamageChanceRange

[Scripting][warning]-getDamageChance

[Scripting][warning]-maxDurability

[Scripting][warning]-damage

[Scripting][warning]-isValid

[Scripting][error]-Error: Failed to get property 'maxDurability'    at setDurability (vienminer.js:22)
    at <anonymous> (vienminer.js:8)

I also tried ++ on damage but then i get "failed to read damage"

wary edge
#

Are you testing it on a custom item or vanilla item?

vagrant flame
#

wood axe

wary edge
#

Could I see your code?

vagrant flame
#

It isnt pretty

amber granite
#

Steal his code 😈

wary edge
#

Hah no worries, I've made my own vein miner before.

amber granite
vagrant flame
#

A friend asked for it for trees specifically. i didnt think i would run into problems like this...

vagrant flame
amber granite
#

._.

vagrant flame
#

Want more i will give you everything.

amber granite
#

I ll tell him i made it ._. too

vagrant flame
#

sure as long as you support it.

#

Seems like a great trade. You can have structura... you can have structura lab. all of it. just have to support it.

amber granite
#

:-:

#

I won't support it

vagrant flame
#

Well... sorry then no deal

amber granite
#

.___. but i steal it

#

What will u do

vagrant flame
#

Cant steel it if it is MIT...

amber granite
#

._.

#

Hmmmm

wary edge
#

Ok so for now, all I'm seeing is setDurability is being called in the playerBreakBlock event subscriber. But I'm not seeing you set the item back to the equippable?

vagrant flame
#

I error out before i can set it back

#

I write my code 1 step at a time (why i dont like golang.... ) making sure bits work as i go so i have less to debug. after i got the read/writes wroking i would set the property back

wary edge
#
const durability_component = componentData.itemStack.getComponent(
    'durability'
) as ItemDurabilityComponent;
if (durability_component) durability_component.damage += 1;
const equippable_component = source.getComponent(
    'equippable'
) as EntityEquippableComponent;
if (equippable_component)
    equippable_component.setEquipment(
        EquipmentSlot.Mainhand,
        componentData.itemStack
    );

How about doing something like this? Ensuring that the durability component does exist. And how about damaing the item first then trying out your code. It could be an issue with full durability?

vagrant flame
#

I did damage the item and also made sure i was in survival

wary edge
#

That is fascinating, I'm wondering if it's this specific event causing an issue? I've never had trouble myself.

vagrant flame
#

I mean it should work in this event right?

wary edge
#

It should because it works for me in my vein miner implementation.

vagrant flame
#

What are your imports for the code above....

wary edge
#

And I'm not seeing anywhere else in your code calling for damaging the durability.

vagrant flame
#

I was just trying to read stuff and it fails to read

#

I removed it because i thought i was doing things wrong.

#

line 24 should have

tool_durability.damage=minedBlocks[player.name].length-1

#

And that should actually be +=... i was trying to learn how unbreaking works and if i had to re-implment the random chance... it was not documented in the docs... so i had not goten to actually writing the damage stuff yet

wary edge
#

Ah unbreaking.

vagrant flame
#

I do the vien miner checks in the "before break" but that is read only... then i do the durability settings in aferevent... and i am not complete on writing the after event code yet...

wary edge
#

According to my docs:

valid ice
vagrant flame
#

and then i was planning on reading durability and writing durability to see how damage wroked...

#

the docs are like 30% complete for this section... and i was confused if damage was "damage taken" or "damage remaining" so was printing things but i couldn't even print them.

wary edge
#

Ah yes, I'm pretty sure damageChance also only works for select vanilla items as well 🤣 .

vagrant flame
#

I thought i was accessing the wrong components so i looped through the methods to see if they were there.

wary edge
#

Huzzah! I recreated your error, Debugging time!

vagrant flame
#

cool.

#

I am only mildly crazy

#

Happy to write up a bug or do whatever is needed. just wanted to make sure i was not doing something stupid first.

wary edge
#

What I'm thinking is due to it being a vanilla item perhaps? It's decrementing it's own durability first which makes it fail getting max durability?

vagrant flame
#

That is interesting... but i also cant get damage

wary edge
#

Ok....this code works:

    let player = event.player;
    const equippable_component = player.getComponent(
        'equippable'
    ) as EntityEquippableComponent;
    const item = equippable_component.getEquipment(EquipmentSlot.Mainhand);
    const durability_component = item.getComponent(
        'durability'
    ) as ItemDurabilityComponent;
    if (durability_component) durability_component.damage += 10;
    console.warn(durability_component.maxDurability);

    if (equippable_component)
        equippable_component.setEquipment(EquipmentSlot.Mainhand, item);
drowsy scaffold
#

how does the getPlayerProfile example that's shown in ServerSecrets for minecraft/server-admin work? I tried running it and it keeps returning the error handling that they try to throw from the auth token not being defined

drowsy scaffold
vagrant flame
#

It has been a long while since i used it. just asking the most common error.. people trying to run that or -network on single player worlds. (mistake i have made)

#

yeah i fail to get durability no mater what i do... If you got any ideas smokey let me know

wary edge
vagrant flame
#

That works.

#

Thanks i can play now

inland merlin
#

does anyone know why does having an "items" folder in any other addon conflicts with herobrines chestformdata addon?? it mixes them up... any work around without adding everyting to it from different addons?

#

oh wait

#
If you are using behaviour packs with items of format 1.16.100 or higher, vanilla item IDs are changed! To remedy this, navigate to scripts/extensions/forms.js and change the constant number_of_1_16_100_items to whatever number of 1.16.100+ custom items your applied pack(s) have.```
valid ice
#

Eayup

steady canopy
valid ice
#

Eayup

inland merlin
valid ice
#

Vanilla IDs get offset

inland merlin
#

makes sense then

#

just depends on the item beh files

#

i guess

valid ice
#

Yeah

inland merlin
#

hmm, thats annoying for compatibility

#

oh well, not too bad

valid ice
#

Custom items get inserted at an aux ID of 256

inland merlin
#

what about packs with multiple versions

#

like 3 packs with 3 different version

#

would i have to update 2 of them

valid ice
#

And the order they are inserted in is different on a world vs bds

inland merlin
inland merlin
valid ice
#

And the order thing is useless unless you want to map custom items to their ID- it’s just a fun fact I threw in there 😛

inland merlin
valid ice
#

Ye

inland merlin
#

still so confusing

#

lmao

valid ice
#

Yep

#

The pack that shows you each icon and its number may help you visualize it

#

It’s a download in the readme

inland merlin
#

ok

#

oh lord

valid ice
inland merlin
#

const number_of_1_16_100_items = 0;

this nubmer

valid ice
#

You don’t need that pack to do it, just need to count the number of custom items you have and that’s it

inland merlin
#

is that possible or negative

#

positive*

#

ill try that

valid ice
inland merlin
valid ice
#

Excellent

dim tusk
inland merlin
#

do i change a number as well?

#

so i can fix that in the future

valid ice
#

It gets added wherever the hell the devs think it should be

inland merlin
#

oh

#

lmao

#

wtf

valid ice
#

And that’s where the pack that shows everything comes into play

inland merlin
#

ohhh ok ty

#

makes sense

valid ice
#

In general, items get added in the unassigned negative values

inland merlin
#

i see

valid ice
#

And in general, the unassigned positive values are for flattened block states

#

I say in general, because bundles were added at 256, and I think the new resin stuff is at 720 or something (the unassigned positives)

inland merlin
#

lol ok now i know how 2 fix ty

#

if needed

valid ice
#

If the items hit the end of the pages shown, you can edit the starting value (think it’s -1000 atm)

inland merlin
#

sounds good, add scrolling with json ui on that id pack?

valid ice
#

It lags as-is, rendering that many icons

inland merlin
#

awh i see

#

so its limited

#

ok

valid ice
#

Yeah

inland merlin
#

it was slow lol

valid ice
#

Just close & reopen the UI to scroll

inland merlin
#

ok

valid ice
#

And hit a /reload to reset

inland merlin
#

yeg

#

yeh

inland merlin
# valid ice And hit a /reload to reset

realy quick, because we are adding custom items those are basically added right? so we can use their typeId to load those in, or do we need to add them all to the end of the id file?

#

like textures

#

or just have them all out in the items folder

valid ice
#

They are already added to the icon list- hence why you need to shift vanilla ones

inland merlin
#

i see, so even if they are deep in a lot of folders it doesn't matter

#

in their own pack

valid ice
#

Correct

inland merlin
#

awhh ok

#

i was just making sure

valid ice
#

If they are available in the world, then they have an ID

inland merlin
#

as i had a code issue, so i have to fix that on my end

#

thx for confirming that

#

making sure i had the logic correct

#

the "shift"

neat hazel
#

What's the error?

mc.system.runInterval(() => {
  const dimension = mc.world.getDimension("overworld");
  const time = dimension.getTime();

  if (time >= 0 && time < 12000) {
    player.sendMessage("Day")
  } else {
    player.sendMessage("Night")
  }
}, 20);
deep yew
#

What is "player"? It's not defined.

neat hazel
deep yew
#

then what's the error of example code...

neat hazel
deep yew
#

it's world.getTimeOfDay()

#

Because the nether and end do not have times, I assume

neat hazel
inland merlin
#

i do havd a custom setup, so maybe thats an issue...

ill have to redownload the main pack i suppose

#

and test

valid ice
inland merlin
#

actual pack

valid ice
#

It's the number that corresponds to that typeId

inland merlin
#

hmm, i think i would be doing it wrong.. i think i need to redownload the orignal

#

pack, i have customized alot of stuff so ill do that myself

#

ill let you know if the original pack as similar issues or not

#

sorry to bother you

valid ice
#

lol nw

solar dagger
#

is this not how you set a value for a block state?

world.beforeEvents.worldInitialize.subscribe(eventData => {
    eventData.blockComponentRegistry.registerCustomComponent('maniacc_fns:random_texture', {
        onPlace: (onPlaceEvent: BlockComponentStepOnEvent) => {
            onPlaceEvent.block.setPermutation(
                onPlaceEvent.block.permutation.withState('maniacc_fns:texture_id' as keyof BlockStateSuperset, 1)
            );
        }
    })}
);

      "states": {
        "maniacc_fns:texture_id": [0,1,2]
      }
neat hazel
#

How to detect the weather?
I want to make a system for when it's raining

thorn flicker
tidal wasp
#

How would you use switch case with getTags()?

#

Since it would return an array

#

Or would i have to spam else if

wary edge
#

Loop through it?

thorn flicker
#

it's still in beta.

solar dagger
thorn flicker
#

so you want the docs?

neat hazel
#

I hope it comes to the official soon

tidal wasp
solar dagger
thorn flicker
thorn flicker
# tidal wasp ?

use a for of loop

for (const tag of entity.getTags()) {
//...
}
tidal wasp
#

No it's block tags

thorn flicker
#

it wont be different, both return an array.

thorn flicker
deep yew
#

What's the best way to load an area that's far from other players using scripts, hopefully not runCommand tickingarea?

#

it only needs to be loaded so a structure can load and place/clear blocks and the area can be unloaded after about 5 or 10 seconds

valid ice
celest abyss
#

?

thorn flicker
#

but yes, you can get a certain tag, just check if the string matches the name of your tag you are searching for.

#

what are you trying to do

celest abyss
#

It is possible to detect when a player is on or inside a block ?
I'm trying to make some blocks like slime or cobweb

kind vault
#

Did any one has this this problem too

dim tusk
#

Guys quick question. Is there a faster way to make the object that returns xyz return x,y,z instead

#

-# nvm I realized join() exits lmfao

shell sigil
#

Guys if the playerInteractWithEntity is events that run if you interact on entity how about when you close the interaction of that entity is there any events or methods

dim tusk
#

Just to make sure, you're talking about ActionFormData, ModalFormData or MessageFormData right?

shell sigil
#

No about Interacting in entity like in villager trading etc

crude bridge
#

How can i get the number of a player xp

#

?

celest abyss
#

How does applyknockbacl work?

dim tusk
crude bridge
dim tusk
#

If I'm correct, the direction is based on the XYZ of the world

#

that's why you would use player.getViewDirection() to make the playrr go to that direction instead

celest abyss
#

and using applyKnockback, is there a way to remove the knockback fall damage?

dim tusk
#

Either way, you can't cancel any damage in scripts only

#

Unless you use resistance.

sleek grove
#

How do you read the selected face from onPlayerInteract?

sleek grove
#

Wait I'm being stupid haha

dim tusk
#

you mean block.permutation

#

Yeah i saw that you typed blockPermutation

sleek grove
#

This was my code. But don't I just need to set the blockPermutation to the new block?

            block.setType("block_name");
            const blockPermutation = block.permutation;
            block.setPermutation(blockPermutation.withState("minecraft:cardinal_direction", face));```
warm mason
dim tusk
dim tusk
sleek grove
#

Yeah now that you said it haha

dim tusk
#

Unlike the cardinal that up in scripts it's Up either way if it's not a valid value it should've returned an error.

wheat condor
#

What's the best way to create a variable that can be rode?? from different addons?

wheat condor
round bone
#

(inter-pack communation)

wheat condor
round bone
wheat condor
twilit tartan
#
import { world, system, EquipmentSlot, EntityEquippableComponent } from '@minecraft/server'
system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
            const inventory = player.getComponent("minecraft:inventory").container;
            const selectedSlotIndex = player.selectedSlotIndex;
            const item = inventory.getItem(selectedSlotIndex);
            console.warn(item.typeId)
            system.run(() => { 
                if (item === 'cg:sword_wood'){
                    item.setLore(["'10% critical hit chance, +1 extra attack damage.'"]); 
                inventory.setItem(item, selectedSlotIndex); 
                }
            });
                  
    }
  })```

i never use SetLore before, and i need to set a lore in the item, is this good?
distant tulip
twilit tartan
#

i dont understand very good that xD

slow walrus
distant tulip
wheat condor
slow walrus
#

you want to store or communicate?

#

IPC is for communication,

#

there is a minified file you can use, but yeah it's kinda big rn

#

next major release should be smaller

wheat condor
#

most likely store a location from the first script that triggers the dataase

twilit tartan
gaunt salmonBOT
# twilit tartan ```js import { world, system, EquipmentSlot, EntityEquippableComponent } from '@...

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 3 errors:

<REPL0>.js:9:21 - error TS2367: This comparison appears to be unintentional because the types 'ItemStack' and 'string' have no overlap.

9                 if (item === 'cg:sword_wood'){
                      ~~~~~~~~~~~~~~~~~~~~~~~~

``````ansi
<REPL0>.js:10:26 - error TS2339: Property 'setLore' does not exist on type 'never'.

10                     item.setLore(["'10% critical hit chance, +1 extra attack damage.'"]);
                            ~~~~~~~

``````ansi
<REPL0>.js:11:41 - error TS2345: Argument of type 'number' is not assignable to parameter of type 'ItemStack'.

11                 inventory.setItem(item, selectedSlotIndex);
                                           ~~~~~~~~~~~~~~~~~

Lint Result

ESLint results:

<REPL0>.js

1:25 error 'EquipmentSlot' is defined but never used @typescript-eslint/no-unused-vars

1:40 error 'EntityEquippableComponent' is defined but never used @typescript-eslint/no-unused-vars

slow walrus
wheat condor
# slow walrus and you want to tell the other scripts not to overwrite it/use the same location...
world.afterEvents.playerSpawn.subscribe(({ player, initialSpawn }) => {
            if (!initialSpawn) return;
            if (!this.#validNamespace) throw new Error(`§c[Item Database] ${namespace} isn't a valid namespace. accepted char: a-z 0-9 _`);
            const plc = player.location;
            if (!this.#sL) {
                this.#sL = { x: plc.x, y: 318, z: plc.z };
                world.setDynamicProperty("storagelocation", this.#sL);
                this.#dimension.runCommand(`/tickingarea add ${this.#sL.x} 319 ${this.#sL.z} ${this.#sL.x} 318 ${this.#sL.z} storagearea`);
            }
            this.#sL = world.getDynamicProperty("storagelocation");
            world.setDynamicProperty("init", true);
            console.log(`§q[Item Database] is initialized successfully. namespace: ${this.#settings.namespace}`)
        });
#

the location must be always the same to not use multiple locations

#

tickingareas*

slow walrus
#

well

distant tulip
twilit tartan
distant tulip
#

why the system.run

twilit tartan
twilit tartan
distant tulip
crude bridge
#

how can i export all the functions of a file in the main file?

twilit tartan
slow walrus
# wheat condor the location must be always the same to not use multiple locations

sounds like you'll have to use an IPC system. setup an emitter that checks if any other databases have been initalized already, and then expects a location value returned, (you can do that with invoke in MCBE-IPC), and then setup a handler in the databases to respond to that. Then have some sort of timeout, where if the pack doesn't get a response , it'll initialize itself and then that pack will become the one that responds.

#

it's a bit complicated, but not terrible

dim tusk
distant tulip
slow walrus
#

I would highly suggest waiting for v3.0.0 of MCBE-IPC if you are going to use it though

#

it's got a lot of changes & improvements

wheat condor
#

my database is alredy 300 lines if ill add yours it will stack up to 1300 and i wouldnt even use half of them

slow walrus
#

yeah, that's why I suggest waiting, it'll be a lot more minified

twilit tartan
wheat condor
#

i think ill just store a structure with a item in it named as the location i think that would work

wheat condor
slow walrus
#

yeah ik, I have a similar itemdb

wheat condor
#

thank you btw

slow walrus
#

no problem

wheat condor
#

like you can set a score only to player

slow walrus
dim tusk
distant tulip
#

you can use a fake player or idk what they call it

wheat condor
#

i need it to be a 1 time write

slow walrus
#

just a fake player

#

to store anything

#

but they would be persistent between world reloads, so not the best option

wheat condor
#

how to they work i never used them

distant tulip
dim tusk
wheat condor
#

i need to write it 1 time and read only it

slow walrus
#

because, the location could change, and if you're checking that the scoreboard location exists already, it'll always be there even if no one initialized it, because it persisted from the last world load

crude bridge
slow walrus
#

export * from './file'

wheat condor
slow walrus
slow walrus
#

yeah exactly

wheat condor
#

to have only 1 location

distant tulip
slow walrus
#

yes

inland merlin
#

@valid ice yous said a week or 2 ago you had your own spawners addon. Do you have that available for download?

slow walrus
#

yeah then a scoreboard should be fine

wheat condor
#

how should i use it?!

slow walrus
#

just have 3 scores for x, y, z

crude bridge
slow walrus
wheat condor
#

but it says only numbers

#

niot strings or loications

slow walrus
#

yeah so use three scores for x,y,z numbers

#

do like a ItemDBLocation objective

wheat condor
#

crazy work

slow walrus
#

and X, Y & Z names

wheat condor
# slow walrus and X, Y & Z names
const qItemDbLoc = world.scoreboard.getObjective('qidb')
qItemDbLoc.setScore('x', player.location.x)
qItemDbLoc.setScore('y', player.location.y)
qItemDbLoc.setScore('z', player.location.z)

like this?!

crude bridge
inland merlin
umbral scarab
#

I need some help setting up the new debugger extension on vscode. According to the microsoft documentation, it says something about "Debug with Minecraft" under run but I don't have that option.

wary edge
umbral scarab
#

Should of done

#
  • installed extension
  • setup loopback
  • opened vscode in the right folder
  • made .vscode subfolder with launch.json
  • changed uuid to script module uuid and localroot to project folder
granite badger
#

is your project javascript or typescript?

umbral scarab
#

js

#

I'd say I messed up the launch.json file out of anything but that wouldn't really explain why the Debug with Minecraft option isn't a thing on vscode would it?

plush moss
#

Is there a way to get the perfekt block where you looking at

#

???

#
system.runInterval(() => {
    for (let player of world.getPlayers()) {
        const item = player.getComponent("inventory").container.getItem(player.selectedSlotIndex);
        const lore = item?.getLore();

        if (item?.typeId === "minecraft:stick" && lore?.includes("blockpicker")) {
            const viewDirection = player.getViewDirection();

            const playerPos = player.location;
            
            const maxDistance = 10;
            
            for (let i = 7; i < maxDistance; i++) {
                const x = playerPos.x + viewDirection.x * i;
                const y = playerPos.y+2 + viewDirection.y * i;
                const z = playerPos.z + viewDirection.z * i;

                const block = world.getDimension("overworld").getBlock({x, y, z});
                
                if (block) {
                    console.warn(`Looking at block at coordinates: ${x}, ${y}, ${z}`);
                    break;
                }
            }
        }
    }
});

i tryed it like this but it gives always the wrong coordinates because of the viewdirection

neat hound
#

Did you look into the parms of view direction

plush moss
#

nvw i found this getBlockFromViewDirection

#

xd

dim tusk
#

it's more precise

#
const { x, y, z } = player.getHeadLocation();
const { block, blockFace, faceLocation } = player.dimension.getBlockFromRay({ x, y: y + 0.1, z }, player.getViewDirection(), { maxDistance: 20 });```
neat hound
#

Because this can return undefined, put into a const, then if object, put into the block, face (not blockFace), facelocation vars

#

But great info... will use it

umbral scarab
#

im sure im being stupid but why is this not working?

switch (event.block.location){
    case {x: 10099, y: -59, z: 10001}:
        world.sendMessage("hi");
        break;
}
past blaze
#

The two object might have the same values, but they are still two separate objects

#

What you'll need to do is use if else statements instead, and test the individual x,y,z values.

umbral scarab
#

ok tyty

neat hazel
#

stopAnimation does this exist?

thorn flicker
deep arrow
#

e

valid ice
dim tusk
#

-# oof didn't read the end of the message lmfao

celest abyss
#

How can I make custom coordinates?

#

Let's say I want to simulate a new dimension using the end, but I want the custom coordinates to appear in the Actionbar

#

I need to detect when a player changes his position and add a value to the x/y/z variable

dim tusk
cold shoal
#

Is it possible to know what type of splash potion projectile entity* hit a block?

#

Typeid only returns splash_potion, components also doesn't return any useful info

dim tusk
#

like entity.hasComponent('item')

cold shoal
#

no, it returns undefined

#

that component is for item entity no? I'm trying to check the splash potion type for a projectile entity

dim tusk
dim tusk
cold shoal
dim tusk
cold shoal
#

hmm, how?

dim tusk
# cold shoal hmm, how?
const potion = ItemStack.getComponent('potion');
potion.potionEffectType;
potion.potionLiquidType;
potion.potionModifierType;```
#

But I don't think you can use this on vanilla items just like dye and food components tho I'm not entirely sure

cold shoal
#

Hmm, I'll test that, thanks! Maybe I can find a workaround

celest abyss
#

How do I fix this?

#
system.runInterval(() => {
  for (const player of world.getPlayers()) {
    if (player.isInWater) {

      let {
        x,
        y,
        z
      } = player.location;
      player.onScreenDisplay.setActionBar(`Cordenadas: ${x}, ${y}, ${z} ` + Object.keys(player.location).map(axis => (player.location[axis]).toFixed(1)).join(" "))
    }
  }
}, 1)

celest abyss
distant tulip
#

that looks complicated for a simple thing
what are you trying to do

celest abyss
dim tusk
#

You made it as let so I assume you are editing it so I just did that.

celest abyss
#

I used

const { floor } = Math;
      player.onScreenDisplay.setActionBar(`${[x, y, z].map(coord => floor(coord)).join(' ')}`)
   ``` it worked
dim tusk
#

dayum. You guys love to conplicate things

#

Meh that's your script tho.

quick shoal
dim tusk
#

That's a sign your improving tho

#

But still complicating simple things 🤷

dim tusk
odd path
#

Can anyone tell me how to identify an open trapdoor?

dim tusk
#

it's based on blocks states

#

block.permutation.getState('open_bit') and bloc.permutation.getState('upside_down_bit')

celest abyss
#

🐒

acoustic basin
#

hey guys! so im trying to use fillBlocks, im trying to fill all blocks from my blockList

const blockList = [
    'minecraft:torch',
    'minecraft:soul_torch',
    'minecraft:redstone_torch',
    'v360:copper_torch',
    'minecraft:lava',
    'minecraft:flowing_lava',
    'minecraft:glowstone',
    'minecraft:sea_lantern',
    'minecraft:lit_redstone_lamp',
    'minecraft:beacon',
    'minecraft:shroomlight',
    'minecraft:lloumelight',
    'minecraft:sculk_catalyst',
    'minecraft:ochre_froglight',
    'minecraft:verdant_froglight',
    'minecraft:pearlescent_froglight'
]```
into air in a 25 block radius from the block that's running this event, its a block that runs the event every 3 seconds, and im currently stuck at this
```js
            block.dimension.fillBlocks(new BlockVolume({ x: x - 25, y: y - 2, z: z - 25 }, { x: x + 25, y: y + 7, z: z + 25 }), 'minecraft:air', {})```
acoustic basin
#

but now, how would i replace blocks with specific permutations to different blocks, also with specific permutations, like this for example, also with fillBlocks json block.dimension.runCommand(`fill ${x - 25} ${y - 2} ${z - 25} ${x + 25} ${y + 7} ${z + 25} v360:unlit_lantern["minecraft:block_face"="up"] replace lantern["hanging"=false]`)

dim tusk
acoustic basin
#

and how do i implement this into fillBlocks

#

so all 'v360:unlit_lantern' with 'minecraft:block_face') === 'up' were replace with 'minecraft:lantern', { 'hanging': false } in a 25 block radius

dim tusk
#

both types and permutation

thorn flicker
#

yes, it accepts blockFilter.

dim tusk
thorn flicker
thorn flicker
#

I see

dim tusk
acoustic basin
#

the thing is im having a couple of lanterns and other blocks, like campfire, so i was first thinking of making a const for object like i was doing with mob mutation

const mutationList = {
    'minecraft:pig': 'minecraft:hoglin',
    'minecraft:hoglin': 'minecraft:zoglin',
    'minecraft:cow': 'minecraft:ravager',
    'minecraft:frog': 'v360:warped_frog',
    'minecraft:villager_v2': 'minecraft:vindicator',
    'minecraft:piglin': 'minecraft:zombie_pigman',
    'minecraft:slime': 'minecraft:magma_cube',
    'minecraft:allay': 'minecraft:vex'
}```
#

like this but blocks

dim tusk
#

so that block will replace that block. But using fillBlocks

#

And you don't want to manually input it?

acoustic basin
#

i just want to get rid of this

dim tusk
#

Me who freaking squinting my eyes rn lol

acoustic basin
#

i already did it for blocks with no permutations specific, just fill those blocks with air, but now, here i need to replace blocks specifically with states, so like the copper campfire with lit state set to true was set with copper campfire with lit state to false, and other blocks, for example, so that's y i thought of using something like i did with entity mutation list, with an object

acoustic basin
dim tusk
# acoustic basin this thing is burning my eyes now
import { BlockPermutation, BlockVolume, world } from "@minecraft/server";

// Command: /fill 0 10 0 20 30 40 tnt["allow_underwater_bit"=true] replace air
const overworld = world.getDimension("overworld");
overworld.fillBlocks(new BlockVolume({ x: 0, y: 10, z: 0 }, { x: 20, y: 30, z: 40 }), BlockPermutation.resolve("minecraft:tnt", { allow_underwater_bit: true }), {
    blockFilter: { excludeTypes: ["minecraft:air"] },
});```
thorn flicker
#

you could probably have more flexibility if you use getBlocks and use getBlockLocationIterator, no?

acoustic basin
#

thats y im asking

#

since im still learning a lot of stuff

thorn flicker
#

im asking for coddy's input

#

mb.

dim tusk
thorn flicker
#

getBlocks also has blockfilter btw

dim tusk
#

I can't test it rn since... I'm lazy as a snail

thorn flicker
dim tusk
#

yeah, just chcked the documentation

#

I guess yeah? He could probably check all blocks in that location that match the id and permutation and fill that location only

thorn flicker
#

you just do

for (const locations of getBlocks(vector_a, vector_b, {includeTypes: yourBlocksToReplace}).getBlockLocationIterator) {
const block = block.dimension.getBlock(locations)
const perm = block.permutation

if (perm.getState('whatever') === false) {
//...
}
 }
dim tusk
#

Daym, I was about to type that 😭

#

I guess not typing it anymore lol

acoustic basin
dim tusk
thorn flicker
#

yeah.

#

its just an example

#

very random

#

lol

acoustic basin
#

on the whole i currently did this

for (const locations of block.dimension.getBlocks(new BlockVolume({ x: x - 25, y: y - 2, z: z - 25 }, { x: x + 25, y: y + 7, z: z + 25 }), { includeTypes: (blockList1) }).getBlockLocationIterator) {
                const block = block.dimension.getBlock(locations)
                const blockPermutation = block.permutation
                if (blockPermutation.withState('hanging', false) || blockPermutation.withState('minecraft:block_face', 'up')) {
                    block.setPermutation(BlockPermutation.resolve('v360:unlit_lantern', { 'minecraft:block_face': 'up' }))
                }
            }```
dim tusk
#

what's inside the blockList1?

acoustic basin
#

this is my blockList1

const blockList1 = [
    'minecraft:lantern',
    'minecraft:soul_lantern',
    'v360:copper_lantern',
    'v360:lush_lantern',
    'minecraft:campfire',
    'minecraft:soul_campfire',
    'v360:copper_campfire'
]```
dim tusk
#

make sure it's purely an array not an object

acoustic basin
#

void, i saw wat u said, but it didnt work as well

acoustic basin
#

noo, its telling about en error on for (const locations of block.dimension.getBlocks(new BlockVolume({ x: x - 25, y: y - 2, z: z - 25 }, { x: x + 25, y: y + 7, z: z + 25 }), { includeTypes: (blockList1) }).getBlockLocationIterator)

thorn flicker
#

still.

#

use getState.

acoustic basin
#

okie

dim tusk
#

It specifically said that? sometimes it says that but the problem is in the next line.

acoustic basin
#

[Scripting][error]-TypeError: value is not iterable at onTick (chiseled_smooth_basalt_bricks.js:124)

#

the line 124 is this

for (const locations of block.dimension.getBlocks(new BlockVolume({ x: x - 25, y: y - 2, z: z - 25 }, { x: x + 25, y: y + 7, z: z + 25 }), { includeTypes: blockList1 }).getBlockLocationIterator)
thorn flicker
#

getBlockLocationIterator()

#

not
getBlockLocationIterator

#

thats on me ig

acoustic basin
#

lol my game crashed

thorn flicker
#

ive had my game crash before when using this

fallow rivet
#

Hello

thorn flicker
fallow rivet
#

I forgot how to change the name of an entity, does anyone know?

acoustic basin
#

yep, cant get into the world at all now

thorn flicker
distant tulip
#

125,500

thorn flicker
#

reassign it.

acoustic basin
#

ive figured it out with fillBlocks and it's not crashing the game

fallow rivet
thorn flicker
acoustic basin
#

basically this is what i did

block.dimension.fillBlocks(new BlockVolume({ x: x - 25, y: y - 2, z: z - 25 }, { x: x + 25, y: y + 7, z: z + 25 }), BlockPermutation.resolve('v360:unlit_lantern', { 'minecraft:block_face': 'up' }), {
                ignoreChunkBoundErrors: true, blockFilter: {
                    includePermutations: [BlockPermutation.resolve('minecraft:lantern', { 'hanging': false }), BlockPermutation.resolve('minecraft:soul_lantern', { 'hanging': false }), BlockPermutation.resolve('v360:copper_lantern', { 'minecraft:block_face': 'up' }), BlockPermutation.resolve('v360:lush_lantern', { 'minecraft:block_face': 'up' })]
                }
            })```
#

array with block permutations for a list of blocks to get replaced with a different block with specific states

thorn flicker
acoustic basin
thorn flicker
#

im happy that you got it working though vlad

acoustic basin
#

a process of learning

#

thank u for the help thought!

thorn flicker
#

lol

#

-# ik what you meant

warm mason
thorn flicker
#

this is the cringiest discord emoji ive ever seen

acoustic basin
#

i dont have nitro to use some kind of different, better sticker

#

but i would if i had nitro

thorn flicker
acoustic basin
#

i'll use a chao gif then, its better than this

thorn flicker
#

yeah, thats way better

#

its wholesome

acoustic basin
#

ye, chao r the cutest thing in the world

fallow rivet
#

Player.isMoving
Is there such a thing?

#

I remember there was

thorn flicker
thorn flicker
thorn flicker
#

however, in beta

#

there's inputInfo

#

where you can pretty much detect WASD I believe.

#

1 sec

thorn flicker
#

player.inputInfo.getMovementVector()

thorn flicker
#

if you want to check it out, but if you want stable use getVelocity like serty suggests.

dim tusk
#

inputinfo is fun to use ngl

hushed ravine
#

How do I spawn an entity outside of a loaded chunk?

warm mason
hushed ravine
#

I tried doing a border block + ticking entity approach

#

I think I'll die before I find a way to make a world border work qwq

#

This works, but not in loaded chunks

warm mason
#

-# I'm not sure if this is related to the scriptAPI

prisma shard
#

hehe

hushed ravine
#

OMG

#

I MADE THE BORDER WORK

prisma shard
#

ok

hushed ravine
#

I literally just had to wait for the player to load the chunk first 😭

#

Thanks to a try and catch

#

And a while

#

Running in a system.run of all things

wheat condor
#

how does this make sense?!

wary edge
#

You should be doing a try-catch.

wheat condor
#

its in afterEvents and i wrappeid also it in a system.run

wary edge
#

Can you try it without putting it in the if statement?

wheat condor
#

still the same issue

#

wait a second

wheat condor
#

282 is the line that has the structureManager.get()

dim tusk
#

kinda weird that it can't be in the same tick just to check names

open urchin
#

does doing something like setting a block work

wheat condor
neat hazel
#

How to detect the biome the player is in?

warm mason
#

-# Waiting for Biome class day 1239878

fleet pewter
#

In beta there is dimension.findClosestBiome

wary edge
celest abyss
#

I'm trying to simulate a custom dimension, how could I make the coordinates different?

I put the real coordinates in an actionbar

fleet pewter
neat hazel
fleet pewter
#

Does /locate biome find biomes smaller than 64x64?

warm mason
distant tulip
#

as i said it is not that precise

#

maybe use filter as Vprufus7 did

celest abyss
#

Does anyone know how to detect if a structure already exists?
Is it with

world.structureManager.getWorldStructureIds.name("mystructure:") 

or something like that?

thorn flicker
#

it returns an array

#

you need to loop through it.

distant tulip
#

also, maybe it is better to use
structureManager.get(id)

thorn flicker
#

right.

#

that would be better.

distant tulip
#

not sure if this throw errors or return undefined tho

thorn flicker
#

it returns undefined when the structure doesnt exist

distant tulip
#

in that case that should be better

gusty bramble
#

Is it possible to give a player an item with NBT data, say a shulker full of an item

celest abyss
#
world.afterEvents.itemUse.subscribe((event) => {
  const player = event.source;
  const item = event.itemStack;
  if (item.typeId === "minecraft:gold_ingot") {
system.runTimeout(() => {
      world.structureManager.place('mystructure:dimension', overworld, location);
    }, 100)
}}
quick shoal
#

And every time spawn dimension check if have state

#

U can try dynamic property

#

@celest abyss

distant tulip
celest abyss
distant tulip
#

same

inland merlin
#

@valid ice

quick question

i noticed that the pack when i added 143 (how many item files are in the other addon with custom armor) was inserted randomly inside the vanilla ones... not at the end. not sure why this is?

#

the id pack

#

the circled one is the last one before the ids are messed up

#

how would i get the items to show at the end?

valid ice
#

That's the neat part, you dont

inland merlin
#

oh lol, well... the custom items are not showing in the form

#

where as half the vanilla ones work.

#

would it still be an error on my end the wrong custom item count?

valid ice
#

Like, they're wrong in the reference form thingy, or the actual pack?

inland merlin
#

they just show as no icon invisible

valid ice
#

When you use the custom item typeId as the icon?

inland merlin
#

just not the custom ones

#

yes

#

the custom item typeId

#

for the form code

valid ice
#

If you want to add custom ones you gotta change the map

#

All the number does is offset vanilla ones, it does not add custom ones in

inland merlin
#

ohhhhh

#

so how should i add the custom ones in after the offset

#

143 offset,

#

and then...

#

i feel so helpless lol

valid ice
#

Remove the offset, and then use the reference pack to add them into the massive map with all the vanilla ones

#

And then manually offset the vanilla ones by adding the offset inside the map (instead of it being calculated separately)

inland merlin
valid ice
#

Yes

inland merlin
#

lmao..... dang it

valid ice
inland merlin
#

i see, so just add all the custom typeIds to the pack and then the offset makes sense

#

ook ill try

covert goblet
#

folks, i'm trying to use the GameTest Framework to spawn a Simulated player, but i keep getting an error on loading the structure. My understanding is i should have an empty structure saved in the behaviour packs structure folder but i'm using the development_behaviour_pack folders, is this the problem??

wary edge
covert goblet
#

yeah, did all that 😞 I'm using jayly's spawn-simulated-player example, but all i get is "failed to load structure" errors.

wary edge
#

Can you load the structure?

#

I've had a similar issue where i had to persist and loading the structure then re-exporting it again.

covert goblet
#

yeah, the /structure laod comamnd works fine, so i know the structure exists,

wary edge
inland merlin
#

i should be good now, it was confusing at first.

#

but now i know how to add custo items to the typeId list properly thanks to the id pack

#

ty

#

for the addon

gusty bramble
#

import * as mc from '@minecraft/server'
import {system, world} from '@minecraft/server'
import {Command} from 'lib/canopy/CanopyExtension';
import  extension from 'config'
const ItemDisplayCommand = new Command({
    name: 'itemdisplay',
    description: 'Shows the amount of items in a stack',
    usage: 'itemdisplay',
    callback: ItemDisplayCommandCallback,
    args: [
    ],
    contingentRules: ['StorageUtilities'],
    adminOnly: false,
    helpEntries: [],
    helpHidden: false
});
extension.addCommand(ItemDisplayCommand);

function ItemDisplayCommandCallback(sender, args){
system.runInterval(() => {
   for (const dimension of ['overworld', 'nether', 'the_end']) {
      for (const entity of world.getDimension(dimension).getEntities({ type: 'minecraft:item' )) {
         const item = entity.getComponent('item');
         entity.nameTag = `§u${item.amount}x §d${item.typeId.replace("_", " ").replace("minecraft:", "")}`;
      }
   }
});
}

[Scripting][error]-Plugin [Storage Utilities V1.1.0 - 1.0.0] - [main.js] ran with error: [SyntaxError: expecting '}' at src/commands/ItemDisplayCommand.js:22
]

whats up here? Like I understand that error but I can’t work out what part is wrong

valid ice
#

).getEntities({ type: 'minecraft:item' )) closing bracket is a ) instead of a }

hybrid island
#

I am trying to make fairy soul from hypixel skyblock but i dont know how to only make it work once so the player cant claim it again here is my current code

 
import { world, GameMode, system } from "@minecraft/server"
import { ActionFormData, ModalFormData } from "@minecraft/server-ui"



world.beforeEvents.playerInteractWithBlock.subscribe(e => {
    let { block, player, itemStack } = e;

    if (block.typeId == "sky:fairysoul") {

    }
})
gentle mist
#

Can someone help me with my code private? I need someone who has knowledge and time please would be so nice

quick shoal
gentle mist
gentle mist
#

I did a duel system

#

All is working but, for a reason sometimes players get tped to a spot they dont get tped

#

Should*

#

Alsp

#

They are stuck there

#

/kill or tp isnt working

#

Only option is to reset the packs

#

But after some rounds its Happening again

#

Here are some examples

#

Private wpuld be good because i would invite someone who can fix that to my github where all codes are and i can send the world private too if needed

hybrid island
hybrid island
#

how to save it for the block?

dim tusk
hybrid island
#

how to get block location

dim tusk
#

worl.setDynamicProperty(Object.values(block.location).join(','), true);

hybrid island
#

ok how to read it

dim tusk
#

Or everyone

hybrid island
#

ya only that player

#

its basccily when you interact with it you get some stuff/scoreboard but you cant interact again

dim tusk
#

Wai.

hybrid island
#

wait a sec

#

tags

#

no that wouldn't work

dim tusk
# hybrid island wait a sec
import { world } from "@minecraft/server";

world.beforeEvents.playerInteractWithBlock.subscribe((e) => {
    const { block, player } = e;
    const blockKey = Object.values(block.location).join(',');

    let list = JSON.parse(world.getDynamicProperty('fairy:' + blockKey) || "[]");

    if (!list.includes(player.id) && block.typeId === '<name>') {
        list.push(player.id);
        world.setDynamicProperty('fairy:' + blockKey, JSON.stringify(list));

        player.sendMessage("You found a Fairy Soul!");
    } else {
        e.cancel = true;
        player.sendMessage("You've already interacted with this Fairy Soul.");
    }
});```
hybrid island
#

thanks

dim tusk
#

It has a flaw btw, when you break that block and place it again, it still store it so make a script that detects placing

dim tusk
round bone
# hybrid island I am trying to make fairy soul from hypixel skyblock but i dont know how to only...
import { world, GameMode, system } from "@minecraft/server"
import { ActionFormData, ModalFormData } from "@minecraft/server-ui"



world.beforeEvents.playerInteractWithBlock.subscribe(e => {
    let { block, player, itemStack } = e;

    if (block.typeId == "sky:fairysoul") {
        const { x, y, z } = block.location;
        const hasClaimed = player.getDynamicProperty(`fairySoul: ${x} ${y} ${z}`) ?? false;

        if (hasClaimed) {
            player.sendMessage("You already claimed this fairy soul.");
            e.cancel = true;
            return;
        };

        // action for claiming
        player.setDynamicProperty(`fairySoul: ${x} ${y} ${z}`, true); // keep this like to track if player has claimed this fairy soul
    };
});
dim tusk
round bone
#

consider moving to a post guys tbh

hybrid island
round bone
dim tusk
#

tho it's easy to convert it to custom components

round bone
hybrid island
#

i don't know how to make custom components can u give me docs tho

dim tusk
#

Huh?
-# this is for codeshark

quick shoal
#

Nothing

dim tusk
hybrid island
#

-# a

quick shoal
#

I just not seriously read it first time

hybrid island
#

gimme docs link

dim tusk
#

Search it yourself, don't always rely on other dude.

drifting ravenBOT
#
HCF Removal and Custom Components

The Holiday Creator Features experimental toggle has been removed. Along with it includes JSON block and item events. This functionality has been replaced with custom components.

Please take a look at the following links to learn more about custom components:

Bedrock Wiki

MS Docs

dim tusk
#

@hybrid island ☝️

hybrid island
#

k thx

dim tusk
#

Your name doesn't match you rn ngl.

hybrid island
#

true

round bone
hybrid island
#

nahhhh

shadow geyser
#

h

gusty bramble
unique acorn
#

send ur code again

gusty bramble
#
import * as mc from '@minecraft/server'
import {system, world} from '@minecraft/server'
import {Command} from 'lib/canopy/CanopyExtension';
import  extension from 'config'
const ItemDisplayCommand = new Command({
    name: 'itemdisplay',
    description: 'Shows the amount of items in a stack',
    usage: 'itemdisplay',
    callback: ItemDisplayCommandCallback,
    args: [
    ],
    contingentRules: ['StorageUtilities'],
    adminOnly: false,
    helpEntries: [],
    helpHidden: false
});
extension.addCommand(ItemDisplayCommand);

function ItemDisplayCommandCallback(sender, args){
system.runInterval(() => {
   for (const dimension of ['overworld', 'nether', 'the_end']) {
      for (const entity of world.getDimension(dimension).getEntities({ type: 'minecraft:item' })) {
         const item = entity.getComponent('item');
         entity.nameTag = `§u${item.amount}x §d${item.typeId.replace("_", " ").replace("minecraft:", "")}`;
      }
   }
});
}

this works but doesn’t show the name at all

wary edge
#

😛 seems we hit a roadblock. Each post can only have 1K members. We're gonna start removing people who haven't chatted in more than a month.

crude bridge
#

Noo

lone thistle
#

and it begins

noble bolt
#

Chat

chilly fractal
#

Yo bois

#

Bois

#

Is there an event for when a server shuts down?

#

Server (bds) not world.

chilly fractal
#

Thanks dude

dim tusk
#

fun part if you use this in single world when you do /reload it triggers it

slow walrus
weak swallow
#

no one can join while it's full

slow walrus
#

they can't message?

#

thats stupid

#

I mean as long as messages aren't removed, a bot to automate that would be fine

wary edge
#

Discord in all its wisdom has decided only 1000 people can be in a forum post thus disallowing new people to join. I doubt that all 1000 members are chatting here daily. All it does is simply make them unfollow the post thus removing them from a post.

slow walrus
#

yeah

#

they do that abritrary number for a bunch of stuff, very strange

distant tulip
#

1000 is kinda a lot, but the way they are handling it is "stupid"

gusty bramble
#

I’m guessing the

{item.amount}x 

Part but not entirely sure

warm mason
gusty bramble
#

Ah

gusty bramble
#

On a similar topic can the name colour be changed based on what stack type it is? Eg: 1 stackable = red. 16 stackable = orange, 64 stackable = lime, (and maybe shulker boxes = purple if that’s possible)

#

I had a look at the itemStack class but couldn’t seem to find anything that separates item stack types

deep arrow
#

I don't believe so

jolly veldt
#

Referring to this message, i would like to ask in this channel, since it is more appropriate, how do i make the inventory show to the player? I've checked the object documentation for the inventory component and there is no method to display it

dim tusk
#

Except server form.

#

That's all, no other UIs
-# exclude npc screen.

jolly veldt
#

So, how is automatic inventory display achieved?

dim tusk
jolly veldt
#

How do i use entities to open inventories then? I would assume it does not involve directly interacting with the entity

amber granite
#

The dopamine dose

amber granite
#

But last time i checked u can only make player jump or sneak i think

#

But u can force him to press buttons

#

@jolly veldt

#

U gotta use beta api

jolly veldt
weak swallow
#

haha

#

2 pings

amber granite
#

._.

#

What u wanna do ?

weak swallow
#

maybe he's just joking

distant tulip
weak swallow
#

do-se

distant tulip
#

just kill me

weak swallow
#

lmfao

chilly fractal
#

Also quick question yall

#

Can i possibly access a player's uuid or xuid or some kind of stable id that never changes?

#

I dont mean the .id of the player, that is an id for them per world. So yea

weak swallow
#

you can't

chilly fractal
#

Yeah i thought so too

#

If i find a way I'll turn my addon open source for later devs

weak swallow
#

.id is the best option

#

or you can do .name 😂

chilly fractal
weak swallow
#

then

#

you can't

chilly fractal
chilly fractal
weak swallow
#

what is the stuff?

chilly fractal
#

Cuz i get more control there

weak swallow
#

why you need unique id for account?

#

isn't it enough with unique uuid per world?

chilly fractal
chilly fractal
weak swallow
#

use name to do it

chilly fractal
chilly fractal
# weak swallow use name to do it

I know, i fricking know, i am literally just asking others who have done something like this, incase someone wants to share with me their knowledge

weak swallow
#

okiiiiiiiiiiii

gusty bramble
#

I’ve found out my item stack display really does not like boxes of items.

~200 boxes of items

#

Vs just ~200 item stacks

#

Is there any way to just make it ignore shulker boxes

remote oyster
gusty bramble
#

Thx

remote oyster
gusty bramble
#

It’s saying typeId is undefined

bright dove
#

static async lightPortal(corner, dimension,  x_oriented) {
        for (let x = 0; x < 4; x++) {
            for (let y = 0; y < 5; y++) {
                let blockpos = Vec3.add(corner, { x: x_oriented ? 0 : x, y, z: x_oriented ? x : 0 });
                let is_edge = x === 0 || y === 0 || x === 3 || y === 4;
                const block = await new Promise((resolve) => {
                    resolve(dimension.getBlock(blockpos));
                });
    
                if (block !== undefined) {
                    if (is_edge) {
                        (BlockPermutation.resolve("gaia:keystone_block"));
                    } else {
                        (BlockPermutation.resolve("gaia:gaia_portal", { "gaia:x_oriented": x_oriented }));
                    }
                }
            }
        }
    }```
#

ive check everything there is

#

what is wrong w this

remote oyster
warm mason
#

And you just create BlockPermutation, but don’t set it

#
                if (block !== undefined) {
                    if (is_edge) {
                        block.setPermutation(BlockPermutation.resolve("gaia:keystone_block"));
                    } else {
                        block.setPermutation(BlockPermutation.resolve("gaia:gaia_portal", { "gaia:x_oriented": x_oriented }));
                    }
                }
gusty bramble
# remote oyster Yea, that is my fault. Slipped my mind. Here: ```js if (!item || item.itemStack...

It seems to be doing the same thing.

I have it set up like this

system.runInterval(() => {
   for (const dimension of ['overworld', 'nether', 'the_end']) {
      for (const entity of world.getDimension(dimension).getEntities({ type: 'minecraft:item' })) {
         const item = entity.getComponent('item').itemStack;
if (!item || item.itemStack.typeId === "minecraft:shulker_box") {
    continue;
}
entity.nameTag = `§a${item.amount}x §7${item.typeId.replace("_", " ").replace("minecraft:", "")}`;
      }
   }
});
}
warm mason
# bright dove ```js static async lightPortal(corner, dimension, x_oriented) { for (l...
static lightPortal(corner, dimension, x_oriented) {
  for (let x = 0; x < 4; x++) {
      for (let y = 0; y < 5; y++) {
          const is_edge = x === 0 || y === 0 || x === 3 || y === 4;
          const block = dimension.getBlock(Vec3.add(corner, { x: x_oriented ? 0 : x, y, z: x_oriented ? x : 0 }))

          if (block !== undefined) {
              if (is_edge) {
                block.setType('gaia:keystone_block')
              } else {
                block.setPermutation(BlockPermutation.resolve("gaia:gaia_portal", { "gaia:x_oriented": x_oriented }));
              }
          }
      }
  }
}
warm mason
remote oyster
remote oyster
warm mason
remote oyster
#

Speak plainly.

warm mason
remote oyster
#

You have me confused with your picture and your previous comment.

#

Ah, nevermind. I see now.

#

Regarding the rest of their code that would be better.

gusty bramble
#

That’s why I’m trying to stop it working for boxes

weak swallow
#

then just

#

optimize it

fast lark
#

How can i detect if a player has the inventory full

#

?

warm mason
warm mason
weak swallow
#

ik

#

but do ===

warm mason
weak swallow
#

bro 💀

subtle cove
#

ip (!empty) clos()

weak swallow
#

but u must check if the container is not undefined

honest spear
subtle cove
remote oyster
#

"Hey, you can write that code 2,147,483,647 different ways so why don't you?"

subtle cove
#

"but wait there's more"

gusty bramble
#

Hence why I’m just removing the ability for it to even check boxes

gusty bramble
#

Yeah ik I stopped it for white boxes as a test

weak swallow
#

just use runjob

#

system.runJob

gusty bramble
#

What would that do?

weak swallow
#

It's like multi-threading

remote oyster
# gusty bramble What would that do?

As you perform long tasks, intermediately you can yield the generator to allow other things to happen very briefly so that you don't block the thread on the main CPU. Think of it as pausing the code then resuming.

weak swallow
#

technically it isn't

gusty bramble
#

How would I use it then (I’m fairly new to all this lol)

weak swallow
#

function* name() {
}
system.runJob(name)

gusty bramble
#

K

weak swallow
#

note: runJob is not an interval function

coral trail
#

Would I need to change anything with this to get the right calculation to match how diamonds drop with Fortune?

const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

export const ruby_ore_loot = world.beforeEvents.worldInitialize.subscribe(initEvent => {
    initEvent.blockComponentRegistry.registerCustomComponent('swp:ruby_ore_loot', {
        onPlayerDestroy(arg) {
            const player = arg.player;
            const container = player.getComponent("inventory").container;
            const heldItem = container.getItem(player.selectedSlotIndex);
            if (!heldItem) return;

            if (!allowedPickaxes.includes(heldItem.typeId)) return;

            const enchantable = heldItem.getComponent("minecraft:enchantable");
            const silkTouch = enchantable?.getEnchantment("silk_touch");
            if (silkTouch) return;

            const fortune = enchantable?.getEnchantment("fortune");
            const fortuneLevel = fortune?.level ?? 0;

            const rubyDrop = () => {
                arg.dimension.spawnItem(new ItemStack("swp:ruby", 1), arg.block.location);
            }

            rubyDrop();

            if (fortune) {
                for (let i = 0; i < randomInt(0, fortuneLevel); i++) {
                    rubyDrop();
                }
            }
        }
    });
});
weak swallow
#

the for will not work

#

so do i <= randomInt(0, fortuneLvel)

gusty bramble
weak swallow
#

or

#

make some variables

#

which contains it's unique id

coral trail
gusty bramble
weak swallow
#

you are right

gusty bramble
#

It seems very complicated to work around