#Script API General
1 messages · Page 51 of 1
If the documentation contains an example for TS, this does not mean that it is only available for TS
well i dont know how to make it js
thanks alot!!!!!
#1067535608660107284 message
doesnt rly help
i have said above

i just want my item name from the item when its dropped
Then use this @dawn zealot
then i got linked something i read it but its ts then im getting redirected ti so many different links
world.getDimension('overworld').getEntities().forEach((entity) => {
if (entity.typeId !== "minecraft:item") return;
const item = entity.getComponent("item");
if (item.itemStack.typeId == 'your:item') {
};
})
says theirs an error at item stack when i used that
Then please show the error.
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?
what about entity, if it breaks a block?
Show your new code
world.getDimension('overworld').getEntities().forEach((entity) => {
const item = entity.getComponent("item");
if (item.itemStack.typeId == 'power:damage_reduction1') {
console.warn("hi")
};
})
mhmmmmmm
if (entity.typeId !== "minecraft:item") return;
world.getDimension('overworld').getEntities({type: 'item'}).forEach((entity) => {
const item = entity.getComponent("item");
if (item.itemStack.typeId == 'power:damage_reduction1') {
console.warn("hi")
};
})
works 👍 think i understand it now
Yeah I would look at the docs if I were you
Is there a way to make fog appear only in certain world heights?
iterate players for every tick and set its fog
with commands, idk if in the latest beta they added fog features
Is there a difference between moveItem and transferItem?
the first one needs to specifiy a slot
moveItem(fromSlot: number, toSlot: number, toContainer: Container): void
transferItem(fromSlot: number, toContainer: Container): ItemStack | undefined
Ok but I mean mechanics wise. Do they do anything different?
Why does transferItem only need to specify one slot?
practicabillity?
Transfer is probably just, try to transfer, it may or may not fail?
because its not transferItems?
moveItem isn't moveItems
Yet it takes two slots
ah sorry
transferItems adds the item to the first available slot
Ah thanks. That explains it
Is setCurrentValue still a function?
I'm trying to modify minecraft:variant through script and it claims it is no longer a function
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
That's bizarre cuz i can't edit the variant
do you have any tags on you?
oops player.nametag is in if block
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??
Nah.
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)
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
id of the cow*
world.afterEvents.entityHitEntity.subscribe(data => {
const {damagingEntity, hitEntity} = data;
switch (hitEntity.typeId) {
case 'cow': primaryMenu(player); break;
}
});
cow -> minecraft:cow
okay thx
hitEntity.typeId + what serty said
there is an event for interactions?
interactions with?
entity
playerInteractWithEntity
afterEvents only work for entities with the itneract component
so use beforeEvents
okay
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
Context??
Try entityVariant.value = something
Tried that prior, is says it is read-only
put it inside a system.run
or use entity properties
I apologise since i never used this before, but how does it differ from regular variants?
idk
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
Do not use commands
You can't compare objects
if you stringify them you can
This is still not always accurate. In this case he needs to use entity.id
was thinking, is there like a best way to prevent someone from taking more kb for a slight amount of time after being hit?
oh, why is that?
uh, well, because he compares an object of the Entity class
well yeah
I thought you meant in general
so in this case it wont be accurate ofc.
it works xD
i mean
/////////////////////////////////////////////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]`);
}
}
});
});
}
}
}
});```
i was thinking like maybe calculating their velocity after getting hi-
wh..
what the shit is that
thats a thang
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
This can't work. You think it works, but it doesn't.
he does it hahahahaa
You think it works, but it doesn't.
How could it not do it, if I already tried it and it works, it's not that I think it does, it's that it does it.
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
Apparently you have enough other conditions. But that's the truth of JS - you can't compare objects. Use entity.id if you want to compare entities
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
hes talking about the object comparing
////////////////////////////////////////////////////////////////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
getTimeOfDay is a function, you don't use it. (getTimeOfDay -> getTimeOfDay())
ah chit, how i forget that xD, thanks!
itemStack.setLore(itemStack.getLore().push([event.target.nameTag]))
Not sure why i get an error from this
you can compare objects, and im this imstance their code was perfectly fine. the game doesnt create new JS objects every time it does something, it'll return the same JS object as long as it exists, so the object for the ev.player and the entity in the getEntities or whatever are the same object, and can be compared
how can i make a repair command
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
Thx
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
Are you trying to set the damage greater than the max durability?
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"
Are you testing it on a custom item or vanilla item?
wood axe
Could I see your code?
Steal his code 😈
Hah no worries, I've made my own vein miner before.
I ll publish it before u hihihihi
A friend asked for it for trees specifically. i didnt think i would run into problems like this...
Ooh as long as you support it. you can have all my code.
._.
Want more i will give you everything.
I ll tell him i made it ._. too
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.
Well... sorry then no deal
Cant steel it if it is MIT...
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?
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
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?
I did damage the item and also made sure i was in survival
That is fascinating, I'm wondering if it's this specific event causing an issue? I've never had trouble myself.
I mean it should work in this event right?
It should because it works for me in my vein miner implementation.
What are your imports for the code above....
And I'm not seeing anywhere else in your code calling for damaging the durability.
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
Ah unbreaking.
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...
yes
yeah... i was trying to use the https://stirante.com/script/server/1.16.0/classes/ItemDurabilityComponent.html#getDamageChance method
Documentation for @minecraft/server
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.
Ah yes, I'm pretty sure damageChance also only works for select vanilla items as well 🤣 .
I thought i was accessing the wrong components so i looped through the methods to see if they were there.
it is damage taken
Huzzah! I recreated your error, Debugging time!
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.
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?
That is interesting... but i also cant get damage
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);
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
are you running on BDS?
I am, though I'm running the BDS locallly
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
You've tried the code I sent above as well? Or is the issue getting durability rather than getting max durability?
You have to define the secrets for BDS beforehand- see https://learn.microsoft.com/en-us/minecraft/creator/documents/scriptingservers?view=minecraft-bedrock-stable#variables-and-secrets
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.```
Eayup
It's because custom items offset vanilla items aux ids i guess
Eayup
huh?
Vanilla IDs get offset
Yeah
Custom items get inserted at an aux ID of 256
what about packs with multiple versions
like 3 packs with 3 different version
would i have to update 2 of them
And the order they are inserted in is different on a world vs bds
awh ok
waht... oh man
Doesn’t matter, if the item format version is over 1.16.100 (aka just not 1.10 items) then they are counted
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 😛
so something like this
"format_version": "1.20.50",
Ye
Yep
The pack that shows you each icon and its number may help you visualize it
It’s a download in the readme

so im tryn to follow the way to change to items that are 1.20.50
how do i find the correct number for 1.20.50 to shift the id's
const number_of_1_16_100_items = 0;
this nubmer
You don’t need that pack to do it, just need to count the number of custom items you have and that’s it
ohhhh ok, so that count amount is what i put here
is that possible or negative
positive*
ill try that
Positive
that works great ty
Excellent
-# ||me who is secretly creating simple vein Miner cause of boredom||
if minecraft adds an item to their base files... how does that get fixed?
do i change a number as well?
so i can fix that in the future
It gets added wherever the hell the devs think it should be
And that’s where the pack that shows everything comes into play
In general, items get added in the unassigned negative values
i see
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)
If the items hit the end of the pages shown, you can edit the starting value (think it’s -1000 atm)
sounds good, add scrolling with json ui on that id pack?
It lags as-is, rendering that many icons
Yeah
it was slow lol
Just close & reopen the UI to scroll
ok
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
They are already added to the icon list- hence why you need to shift vanilla ones
i see, so even if they are deep in a lot of folders it doesn't matter
in their own pack
Correct
If they are available in the world, then they have an ID
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"
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);
What is "player"? It's not defined.
Player is just an example
then what's the error of example code...
This part of the code is giving an error
const time = dimension.getTime();
Ok, I'll test it.
wait why does typeIdtoID exist, does it use that for custom items?
the custom items from the other pack aint showing
i do havd a custom setup, so maybe thats an issue...
ill have to redownload the main pack i suppose
and test
Is that the one in the test pack or the actual
actual pack
It's the number that corresponds to that typeId
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
lol nw
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]
}
How to detect the weather?
I want to make a system for when it's raining
block.setPermutation(block.permutation.withState('name', value))
How would you use switch case with getTags()?
Since it would return an array
Or would i have to spam else if
Loop through it?
dimension.getWeather()
it's still in beta.
thanks for copying and pasting the docs
?
wtv it is that you gave me doesnt help
im not going to send you anything if you are going to be sarcastic. If you just asked me for the docs I would've provided.
use a for of loop
for (const tag of entity.getTags()) {
//...
}
No it's block tags
that would be nice
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
Oh yeah, it's runCommand tickingarea
It is possible to get a certain tag
?
if you just want to check if the entity has a tag, just use hasTag()
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
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
Did any one has this this problem too
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
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
just test if the fork is canceled
Just to make sure, you're talking about ActionFormData, ModalFormData or MessageFormData right?
No about Interacting in entity like in villager trading etc
Ahh. No.
How does applyknockbacl work?
Player.level
Thx
Player.applyKnockback(directionX, directionZ, horizontalStrength, verticalStrength)
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
and using applyKnockback, is there a way to remove the knockback fall damage?
wdym by knockback fall damage?
Either way, you can't cancel any damage in scripts only
Unless you use resistance.
How do you read the selected face from onPlayerInteract?
face
that's it.
Wait I'm being stupid haha
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));```
|| Why name variables this way if it shortens the name length by 1 character? ||
Why not just block.setPermutation(BlockPermutation.resolve('<id>', { name: value, name: value })
I don't even know 😭 I kinda hate that too unless it has other sub data's we can say.
Yeah now that you said it haha
Btw the face iirc returns uppercase
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.
What's the best way to create a variable that can be rode?? from different addons?
some IPC?
idk what does means
(inter-pack communation)
yes
the way you communicate between 2 or more packs
gonna do a major release soon
yeah couse i needed some for my item database couse it has a problem with tickingareas limits
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?
what dose it use? scoreboards?
i dont understand very good that xD
scriptevents
seem right, try it
ah, nice
1k lines?! i need something simple to store a small location
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
most likely store a location from the first script that triggers the dataase
Dont works
Debug result for [code](#1067535608660107284 message)
Compiler found 3 errors:
[36m<REPL0>.js[0m:[33m9[0m:[33m21[0m - [31merror[0m[30m TS2367: [0mThis comparison appears to be unintentional because the types 'ItemStack' and 'string' have no overlap.
[7m9[0m if (item === 'cg:sword_wood'){
[7m [0m [31m ~~~~~~~~~~~~~~~~~~~~~~~~[0m
``````ansi
[36m<REPL0>.js[0m:[33m10[0m:[33m26[0m - [31merror[0m[30m TS2339: [0mProperty 'setLore' does not exist on type 'never'.
[7m10[0m item.setLore(["'10% critical hit chance, +1 extra attack damage.'"]);
[7m [0m [31m ~~~~~~~[0m
``````ansi
[36m<REPL0>.js[0m:[33m11[0m:[33m41[0m - [31merror[0m[30m TS2345: [0mArgument of type 'number' is not assignable to parameter of type 'ItemStack'.
[7m11[0m inventory.setItem(item, selectedSlotIndex);
[7m [0m [31m ~~~~~~~~~~~~~~~~~[0m
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
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*
well
if (item === 'cg:sword_wood')
to
if (item.typeId === 'cg:sword_wood')
i do that, and i have this
why the system.run
idk, i just use a code that i see here xd
what in line 10
how can i export all the functions of a file in the main file?
inventory.setItem(item, selectedSlotIndex);
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
Shinki. Don't use the debugger here 😇
switch the args places
that sounds not so easy'
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
my database is alredy 300 lines if ill add yours it will stack up to 1300 and i wouldnt even use half of them
yeah, that's why I suggest waiting, it'll be a lot more minified
Thanks, now it works, but when i dont have anything in the hand i have this
i think ill just store a structure with a item in it named as the location i think that would work
item?.typeId === '....'
not a bad idea actually
my database alredy uses this approach to save items in an entity in a structure
what about scoreboard
yeah ik, I have a similar itemdb
thank you btw
no problem
arent scoreboards related to players?
like you can set a score only to player
they're persistent though
They could use fakenames
you can use a fake player or idk what they call it
i need it to be a 1 time write
nah you can use "dummy" names
just a fake player
to store anything
but they would be persistent between world reloads, so not the best option
how to they work i never used them
yeah, can be a good or bad thing
why not?
instead of using @s you put "name"
i need to write it 1 time and read only it
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
sorry
export * from './file'
why would it change? my database needs a Fixed location for the tickingarea
well you said the databases could use different locations. What if one database loads before the other, and this time it's using a new location
thats what im trying to fix
yeah exactly
to have only 1 location
you can do that?
yes
@valid ice yous said a week or 2 ago you had your own spawners addon. Do you have that available for download?
ah holdup nvm I get what you mean
yeah then a scoreboard should be fine
how should i use it?!
just have 3 scores for x, y, z
thx
imma let someone else explain because it's 4am. But it isn't that hard. Check out the docs, you should figure it out pretty easy
ok
but it says only numbers
niot strings or loications
crazy work
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?!
I do not
Ok 👍 np
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.
Did you follow the docs step by step?
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
is your project javascript or typescript?
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?
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
Did you look into the parms of view direction
use getBlockFromRay
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 });```
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
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;
}
You can't directly compare objects
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.
ok tyty
stopAnimation does this exist?
no
e
😭
simple fix 🤷
const { x, y, z } = player.getHeadLocation();
const blockData = player.dimension.getBlockFromRay({ x, y: y + 0.1, z }, player.getViewDirection(), { maxDistance: 20 } );
if (blockData) {
const { block, face, faceLocation } = blockData;
// ...
}```
-# oof didn't read the end of the message lmfao
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
Get the center of your dimension first then subtract that to current coordinate of the player.
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
can you get the ItemStack of the splash potion as an Entity?
like entity.hasComponent('item')
no, it returns undefined
that component is for item entity no? I'm trying to check the splash potion type for a projectile entity
then you can't.
I'm trying to check if you can since there's potion component in items
if this works, is it possible to get the potion type of an item stack?
^ yeah but since it returns undefined so I guess you can't.
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
Hmm, I'll test that, thanks! Maybe I can find a workaround
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)
Math.floor(x)
Replace toFiex(1) with Math.flor(x)?
that looks complicated for a simple thing
what are you trying to do
system.runInterval(() => {
for (const player of world.getPlayers()) {
if (player.isInWater) {
let { x, y, z } = player.location;
x = Math.floor(x);
y = Math.floor(y);
z = Math.floor(z);
player.onScreenDisplay.setActionBar(`Cordenadas: ${x}, ${y}, ${z}`);
}
}
}, 1);```
You made it as let so I assume you are editing it so I just did that.
I used
const { floor } = Math;
player.onScreenDisplay.setActionBar(`${[x, y, z].map(coord => floor(coord)).join(' ')}`)
``` it worked
same
Fr
As what Minato said too
Can anyone tell me how to identify an open trapdoor?
I already gave you the states
it's based on blocks states
block.permutation.getState('open_bit') and bloc.permutation.getState('upside_down_bit')
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', {})```
okey, i've figured this out lol
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]`)
import { BlockPermutation } from '@minecraft/server';
if (Block.typeId === 'v360:unlit_lantern' && Block.permutation.getState('minecraft:block_face') === 'up') {
Block.setPermutation(BlockPermutation.resolve('minecraft:lantern', { 'hanging': false });
}```
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
iirc the options of the fillBlocks has include exclude
both types and permutation
pf
beat me
me first 😝


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
so that block will replace that block. But using fillBlocks
And you don't want to manually input it?
i just want to get rid of this
Me who freaking squinting my eyes rn lol
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
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"] },
});```
you could probably have more flexibility if you use getBlocks and use getBlockLocationIterator, no?
i dont know
thats y im asking
since im still learning a lot of stuff
I guess soo? I rarely touch fillBlocks.
getBlocks also has blockfilter btw
I can't test it rn since... I'm lazy as a snail
fair
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
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) {
//...
}
}
it just checks for block, without permutations...
uhhhh. block.permutation.getState() exists
so just this said getBlocks is undefined, so i did 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), but now it throws the error at this line that vlaue is not iterable
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' }))
}
}```
what's inside the blockList1?
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'
]```
make sure it's purely an array not an object
void, i saw wat u said, but it didnt work as well
getState, not withState
reference here
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)
okie
It specifically said that? sometimes it says that but the problem is in the next line.
please show the error.
[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)
lol my game crashed
ive had my game crash before when using this
Hello
hi
I forgot how to change the name of an entity, does anyone know?
yep, cant get into the world at all now
get the nameTag property
reassign it.
ive figured it out with fillBlocks and it's not crashing the game
cool.
This was what was needed
entity.nameTag = "item.kaos:backpack"
yeah, thats reassignment.
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
sorry for over-complicating it then
nah that's toattly fine
im happy that you got it working though vlad
ill keep my thoughts helpful, yup
lol
-# ik what you meant
-# You're suspiciously happy
-# vlad is cool
this is the cringiest discord emoji ive ever seen
i dont have nitro to use some kind of different, better sticker
but i would if i had nitro
there's the bedrock addons emojis you could send
i'll use a chao gif then, its better than this
oh, right, i forgot about them lol
ye, chao r the cutest thing in the world
no
that's molang queries you are probably thinking of.
Yea
however, in beta
there's inputInfo
where you can pretty much detect WASD I believe.
1 sec
there's something else in beta.
Documentation for @minecraft/server
player.inputInfo.getMovementVector()
^
if you want to check it out, but if you want stable use getVelocity like serty suggests.
inputinfo is fun to use ngl
How do I spawn an entity outside of a loaded chunk?
This is impossible
Aw man
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
-# I'm not sure if this is related to the scriptAPI
hehe
ok
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
how does this make sense?!
Becaues it can't access the get Method therefore it errors out?
You should be doing a try-catch.
why cant it acces
its in afterEvents and i wrappeid also it in a system.run
Can you try it without putting it in the if statement?
ill try
still the same issue
wait a second
nah it doesnt work either
282 is the line that has the structureManager.get()
Can't you try doing the system.run trick?
kinda weird that it can't be in the same tick just to check names
does doing something like setting a block work
i am using after events and also this
How to detect the biome the player is in?
This is impossible
-# Waiting for Biome class day 1239878
In beta there is dimension.findClosestBiome
shakes head does not work if biome is smaller than 64x64.
I'm trying to simulate a custom dimension, how could I make the coordinates different?
I put the real coordinates in an actionbar
Clearly the api thinks size of biome matters. I wonder why it doesn't find biomes smaller than that
???
Sad
Does /locate biome find biomes smaller than 64x64?
You will have to check all the biomes and choose the closest one, this is time consuming and has a high performance cost
Does anyone know how to detect if a structure already exists?
Is it with
world.structureManager.getWorldStructureIds.name("mystructure:")
or something like that?
no
it returns an array
you need to loop through it.
also, maybe it is better to use
structureManager.get(id)
not sure if this throw errors or return undefined tho
it returns undefined when the structure doesnt exist
in that case that should be better
Is it possible to give a player an item with NBT data, say a shulker full of an item
I want to make it so that if the structure already exists it is not generated again.
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)
}}
Give it a state when spawned
And every time spawn dimension check if have state
U can try dynamic property
@celest abyss
not directly
the only way is pre saved items using structure
I'll try
Sadness
same
@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?
That's the neat part, you dont
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?
Like, they're wrong in the reference form thingy, or the actual pack?
they just show as no icon invisible
When you use the custom item typeId as the icon?
yeah, it still seems the vanilla icons work normally. its so strange lol
just not the custom ones
yes
the custom item typeId
for the form code
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
ohhhhh
so how should i add the custom ones in after the offset
143 offset,
and then...
i feel so helpless lol
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)
i have to add their typeId into the typeIds.js
Yes
awh so large custom packs with a billion armor is a pain
lmao..... dang it

i see, so just add all the custom typeIds to the pack and then the offset makes sense
ook ill try
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??
Try typing /reload all and /structure load or whatever the command is then run the gametest command.
yeah, did all that 😞 I'm using jayly's spawn-simulated-player example, but all i get is "failed to load structure" errors.
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.
yeah, the /structure laod comamnd works fine, so i know the structure exists,
Yo yo Scripting Peeps. Please take the survery: https://discord.com/channels/523663022053392405/1329975398586515478
nuh uh
i've been doing alot of testing and such.. and have learned alot from the offsets... and the custom items.. etc. etc...
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
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
).getEntities({ type: 'minecraft:item' )) closing bracket is a ) instead of a }
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") {
}
})
What is fairy soul
Can someone help me with my code private? I need someone who has knowledge and time please would be so nice
Just directly say what U want to do
I have a problem idk why this happen
What are U making
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
just so like if i interact with it it saves it and i cant interact with it again i tried but i dont think i can save dynamic properties on blocks
Use world 🤷
how to save it for the block?
Make the id is block location
how to get block location
worl.setDynamicProperty(Object.values(block.location).join(','), true);
ok how to read it
Wait when player interacted with the block only that player can't interact
Or everyone
ya only that player
its basccily when you interact with it you get some stuff/scoreboard but you cant interact again
Wai.
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.");
}
});```
thanks
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
wait, it's a custom block right? Why not just use custom components? It's already stable
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
};
});
wdym
What I said is very straightforward already.
consider moving to a post guys tbh
like i mean what is custom components
you can add to block/item etc. custom components, which will be like reusable parts of script API code for these elements
ok
tho it's easy to convert it to custom components
yeah
i don't know how to make custom components can u give me docs tho
Huh?
-# this is for codeshark
Nothing
Read it properly 😭
-# a
I just not seriously read it first time
Docs exist 🤷
gimme docs link
Search it yourself, don't always rely on other dude.
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
- Block Events
- Block Events Migration to Custom Components
- Item Events
- Item Events Migration to Custom Components
MS Docs
@hybrid island ☝️
k thx
Your name doesn't match you rn ngl.
true
Problem Creator
nahhhh
h
It’s still giving that error
send ur code again
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
😛 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.
Noo
and it begins
lul
Chat
Yo bois
Bois
Is there an event for when a server shuts down?
Server (bds) not world.
Thanks dude
fun part if you use this in single world when you do /reload it triggers it
what does that even do? remove their messages as well?
no
no one can join while it's full
they can't message?
thats stupid
I mean as long as messages aren't removed, a bot to automate that would be fine
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.
1000 is kinda a lot, but the way they are handling it is "stupid"
Ok ok turns off the issue was the item.json file I fixed it and this is the result. Any ideas what’s causing this?
I’m guessing the
{item.amount}x
Part but not entirely sure
const item = entity.getComponent('item').itemStack;
Ah
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
I don't believe so
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
you can't display ui in scripts
Except server form.
That's all, no other UIs
-# exclude npc screen.
So, how is automatic inventory display achieved?
Wym
What? That ain't possible
How do i use entities to open inventories then? I would assume it does not involve directly interacting with the entity
it ~~dose ~~ does
The dopamine dose
I think, u can use new api features to make play open his inventory
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
My guy one ping is enough 😭
maybe he's just joking
dude i was spelling it wrong the whole time
the search for "dose" is full of my messages
do-se
just kill me
lmfao
I'm planning to use this for my discord relay, you probably know it, just any event that happens in mc is relayed into discord and any discord message is relayed into mc.
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
you can't
Yeah i thought so too
If i find a way I'll turn my addon open source for later devs
Nah, i need it for external server side stuff
.name is their gamertag which makes it much much harder to do my stuff but yea its probably the most viable option
I know, i am just asking incase someone knew a workaround or something.
what is the stuff?
Basically api end point, using cloudflare workers
Cuz i get more control there
Uuid, universal id, i need it for getting a player's skin's head or their xbox avatar. Not sure what is more easier.
Nope
use name to do it
Also its id, not uuid, it's only unique to the world.
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
okiiiiiiiiiiii
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
This is the code
if (item.itemStack.typeId === "minecraft:shulker_box") {
continue;
}
Thx
Put it under const item = entity.getComponent("item");
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
Yea, that is my fault. Slipped my mind. Here:
if (!item || item.itemStack.typeId === "minecraft:shulker_box") {
continue;
}
const block = await new Promise((resolve) => {
resolve(dimension.getBlock(blockpos));
});
``` why?
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 }));
}
}
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:", "")}`;
}
}
});
}
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 }));
}
}
}
}
}
thanks so much !
item.itemStack.typeId -> item.typeId
You need the item stack to know what the actual item is of the item.
What about it? Not following?
?
Speak plainly.
What? I don't understand
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.
the tps 💀
That’s why I’m trying to stop it working for boxes
if (player.getComponent('inventory').container.emptySlotsCount == 0)
Thx
===
No difference
I'm used to writing ==, I won’t rewrite something if there’s no difference
bro 💀
ip (!empty) clos()
actually you can also do ```js
if (!player.getComponent('inventory').container.emptySlotsCount)
but u must check if the container is not undefined
it is difference
cod translated succezfuli, yw ;-;
"but wait there's more"
It is……… boxes just have a lot of NBT data that it’s apparently checking too
Hence why I’m just removing the ability for it to even check boxes
btw it's possible
Yeah ik I stopped it for white boxes as a test
What would that do?
It's like multi-threading
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.
technically it isn't
How would I use it then (I’m fairly new to all this lol)
function* name() {
}
system.runJob(name)
K
note: runJob is not an interval function
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();
}
}
}
});
});
when the randomint is 0
the for will not work
so do i <= randomInt(0, fortuneLvel)
Could I not make it run once for boxes and after that stop it running for them as they can’t stack anyway
add dynamicProperty
or
make some variables
which contains it's unique id
There is a rubyDrop() before the for that garuntees at least 1 ruby drops. I was mainly wondering about the formula to make more drop with fortune to match the rates on this page
https://minecraft.fandom.com/wiki/Fortune
I’ll go have a look how to do that
oh I couldn't see the call
you are right
matches
I have no clue what I’m looking at rn lol it might be better to just not have it for boxes tbh
It seems very complicated to work around
