#Script API General
1 messages · Page 116 of 1
lmao
Is anybody else having issues when using the debugger in vsCode after this last update?? Whenever I try to put some breakpoints in, the game just freezes without even hitting them
what's the shortcut for opening the creator settings again?
Where can I find the local cache in the latest update 😭
Could I use the textfield in ModalFormData to make players put in a set of coordinates that I can use?
Yea. Store their input as a variable and use it later. Keep in mind that it has to be a valid coordinate, or vector 3
I get storing the input as a variable, but doesn't textField output a string? If it does then how would I actually use the input variable
There are a few ways, one that comes to my mine atm is just splitting the string at each space, and then using Number() on each of the strings, assuming the input is formatting correctly (18 64 -67)
U can then turn that into a vector 3 if ur using player.teleport
I'm sure there's better ways but that's just what comes to mind
Got it, thank you for the help!
Ctrl+H
Can i detect player holding item?
"getComponent("minecraft:equippable").getEquipment("mainHand")"
Works?
That's for the content log, creator settings doesn't get any shortcut key
oh yeah mb 👍
are there ways to hide chat hud? i dont seem to find native methods for it
its possible to get the position of the locate structure command and use it?
I want to make a database with placed structures
No.
😢
hmm any idea of how can I achieve it? cause using entity needs the chunk to load in order to activate the script
hello i use the beforeEvents playerPlaceBlock and playerInteractWithBlock for my anti grief system, but the interactWithBlock is also getting triggered on player block place this breaks my system because those players without interactWithBlock permission but with placeBlock permissions cannot also place blocks
what would be your move here?
check if the typeID of itemstack on interact is a type of block
hhhhhhhh i still cant figure out how to deal with swing event and hit event not firing at the same tick
there's a method in the newest preview to locate generated structures
Much fun had with getting commands to work.... who knew... I am not the Owner of the worlds I randomly create... I wonder who is?
Hello good morning a question I have my Custom Command addon from the / well apart from this addon I put a ui menu with its Custom Command so that it opens through /menu but when activating the two addon and entering the world only 1 will work Any solution that works both ?
rlly? how?
i think its on the dimension class
Do your custom commands have their own unique namespace? Minecraft will try to create aliases for commands by default so you can easily type something like /menu but if there are two add-ons with conflicting custom commands then the (I believe) first command that gets registered will be properly referenced.
Otherwise you need to use the full name of your command like /ns:menu where ns: is your namespace for the add-on
looking for it rn and nope
But If in the other complete the menu that has its Custom /cust:menu command and when they conflicted it does not appear only that of the Custom Command
Thank you!
Documentation for @minecraft/server
wait, why it needs location as parameter?
oh, its not to find closest structures, its just trying to find a structure at coordinates
I'm going to say something more understandable If the menu addon chat comes first, only the /menu works.
- If the Custom Command comes first, everything but the /menu works.
This suggests that both addons are registering conflicting commands, and the one that loads first is left with control of the commands
Remember that they are /cust:menu
Do both add-ons contain the same custom commands for /menu and the same namespace?
You would want to have unique namespace between add-ons typically something like /cust1:menu and /cust2:menu so that they don't conflict.
Only time you may share would be creating dependant add-on with additional custom commands that you know would not conflict.
Aka having addon 1 have /cust: namespace for custom commands and second pack add-on 2 could use the same /cust: namespace so long as the commands in addon 2 are different.
You are using custom commands for both add-ons?
Or one has custom commands and other uses chat based command system?
I mean, look at the Custom Command I have the /cust:lobby /cust:survival and the menu one I put /adm:menu
This is the Custom Command add-on @knotty salmon
And this Custom Menu apart is another addon
@summer cloud
👋
its Mainhand not mainHand
/tick freeze for bedrock?
u can do that with jobs
@knotty salmon
will they ever fix the fucking pfid not returning the players pfid
can we get shulkers' items via itemInventoryComponent?
just bundles
is this reliable?
const AllBlockIDs = BlockTypes.getAll().map((blocktype) => blocktype.id)
world.beforeEvents.playerInteractWithBlock.subscribe((e)=>{
//if placing a block then dont cancel
if (AllBlockIDs.includes(e.itemStack.typeId) && e.player.hasTag("CanPlaceBlock")) return;
if (e.player.hasTag("CanInteract")) return;
e.cancel = true
...
})
not reliable on some cases like if player uses a dirt block in hand to interact with a button etc
What just happened to minecraft?
Mojang decided to give us a "try to figure it all out" quest.
i just found it
AppData\Roaming\Minecraft Bedrock\Users\Shared\games\com.mojang
They just moved it in the same spot as java minecraft
The new version feels a lot faster but a lot of stutter
The only thing I liked about this update is .getAABB() and auto detection of beta-APIs version
what is getAABB?
Maybe... my friend said it looks like they optimized something, but I didn't notice anything.
It's like getting an entity collision box
i noticed it a lot, the game is far more responsive it feels more like java now
Well... then cool.
After updating, I can barely break 20 fps, making the game basically un playable
Mhmm yeah if they have different namespace then they shouldn't conflict.
Doesn't even seem to have the same custom commands using /adm:menu I don't see another /cust:menu that could cause an issue.
Do you happen to get any console warnings when loading with both add-ons?
Does anyone know why scripting does not work in education edition even with expriements enabled?
I will say I'm fairly new to bedrock scripting so overall take what I say with a grain of salt, but generally understand basic programming concepts and scripts.
Overall not seeing anything off the bat from your commands that would be causing issue, perhaps just checking output logs will help narrow down the issue.
wdym, theres actually teachers who are already using it iirc
as for the recent update, what exactly is not working?
I have expriements enabled and when I try to run scripting code using an addon nothing runs but it works on bedrock
Here’s it for example
Just a quick one but is there any way to make a debug text only show in one specific dimension?
I didn't repair anything, no console error
prob better to move it to a post
The only way is to join the menu addon with the Custom Command, but I don't want that, I want the addon separately, so I don't know what to do :/@knotty salmon
const newitem = new ItemStack('minecraft:dirt', 1);
bundle?.getComponent('inventory')?.container.addItem(newitem);
Anyone got the bundle item inventory to add an item to itself?
Do you need to re-set the bundle to the container it's in? @wary edge
Are you asking I need to do that or if I'm comfortable?
😭
Yeah thank you, I needed to re set it.
Im unsure if this could be my code but is there a way to wait for the entity to be valid on the after entity spawn event?
Cause im having issue with it just not being valid
entity.isValid?
yeah but how can I wait till it is
Is it spawning at the edge of your simulation distance?
and or what all is avalible when its not valid
nope
is there a way to check why its invalid?
cause my guess is cause my script could be removing it before it runs
yep that was the case
ended up adding a tag after it spawned and checking before its removed if it has that tag
Remind me again, does cooldown actually do anything in scripting? Like why does it still trigger itemUse even though it's in cooldown.
You can't.
there is no way?
No since we can't access equippable.
is there anyway to check if they have any item?
in their inventory yes, just not in their equipment slots.
entity.getComponent('inventory')
https://stirante.com/script/server/2.3.0/classes/EntityInventoryComponent.html
Documentation for @minecraft/server
for exampl now in front of me a zombie carrying a sword and wearing some armors is there a way to read those items and remove them from him?
smokeystack answered this already.
no
and why they have this?
I dont think they have inventory
so i can have access to the inventory?
you cannot access the items in the armor/hand slots.
to read them you need to access them.
ehaaa
you use a command in script to replace the item though.
can i replace with a null item?
just replace it with air.
how can i know the slot number of this item
are asking how to select what slot to replace in the command?
what does replace command ask for?
this slotID how to get it?
you cant.
😭 then how can i replace an item from zombie hands or somthing
dude
input the slot type.
i thought you meant how to retrieve the slot from the command when it runs
🙏🏻 in arabic we say "اهااااااااااااا" when we understand somthing sooo it is like ehaaaa
lol
so like "aahh"
yea expres stupidity
🤓 im dumb anyway lol
just uninformed, there's a difference
It is possible to just test if they have any in their main hand?
again, not possible.
the main hand is an equipment slot
wasnt sure if you could maybe do it with commands tho
you can use the testfor command in scripts, and then check the success count.
I want any item tho, I dont think testing for air works
?
have you tried?
yeah
found a solution by looking up stuff
const command = entity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 keep air')
if (command.successCount > 0) {
// your code
}
there's a replaceMode in the replaceItem command, which I didnt know about.
np
just gonna be a pain for all 5 slots
actually
theres a slot type that covers all equipment slots
should work
doesnt seem like it
nope, i tested aswell
says an error occur when performing this command
same here
TwT
you could've just used a for loop
Wdym
@wheat plaza (referencing your ping i just didnt wanna type in that discussion post0 sorry im not trying to do hover text rn what im tryna do is make a information menu so ill have a big grid of information boxes with each wepaons texture to the right, like how i have the buttons currently set up, just with more text and cant be interacted with
it alr
for button mappings, to_button_id, is there a way to open a form im making a return button?
"button_mappings": [
{
"from_button_id": "button.menu_select",
"to_button_id": "button.close",
"mapping_type": "pressed"
},
{
"from_button_id": "button.menu_ok",
"to_button_id": "button.close",
"mapping_type": "focused"
}
]
button.back didnt do anything
I can't speak to the issues with its functionality, but another valid way to write that code is with a loop, such as this forEach:
const slotType = ['weapon.mainhand','weapon.offhand', 'armor.head', 'armor.chest', 'armor.legs', 'armor.feet']; // preferably defined somewhere outside of a loop, such as in the header section
let isSuccess;
slotType.forEach(slot => {
if (!(isSuccess = e.runCommand(`replaceitem entity @s slot.${slot} 0 keep air`).successCount)) break;
});
if (!isSuccess) continue;
The way you wrote it is perfectly valid syntax, but using a loop cuts down on repetition of code, which can be good practice for reusability, extensibility and debugging, even if it's a little more complex to write initially. Some would say it's more straightforward the way you wrote it though. It's really up to the coder and what's easiest to use and understand for the particular purpose.
Anyone here got some "blocks between client and server do not match" Error with their addons?? I am using the same version of the addon.
Same minecraft version from google play and launcher (microsoft store)
This just happened after the update of switching from GDK (my guess) cause before it was working fine.
Mm, this would not work. forEach() cannot be interrupted with break in this way. I would do use a for..of loop, then label the statement that MisledWater wishes to continue with.
const slotType = [
'slot.weapon.mainhand',
'slot.weapon.offhand',
'slot.armor.head',
'slot.armor.chest',
'slot.armor.legs',
'slot.armor.feet',
];
// Use the label "outerLoop" to identify this loop
outerLoop: for (const something of everything) {
/* if ... */ for (const slot of slotTypes) {
if (!e.runCommand(`replaceitem entity @s ${slot} 0 keep air`).successCount) {
// Using the label
continue outerLoop;
}
}
// ...
}
Are we ever getting entityhurtbeforeevents?
we dont know.
Do we at least know the reverse engineered damage formulae?
For example taking the damage we would take in full armor and converting to it without
I dont know.
It's kinda frustrating, there is so much I want to do with the player's health, incoming damage and stuff like that but can't
there's alot missing.
Wiki has some in-depth articles on damage and armor formulae.
https://minecraft.wiki/w/Damage
https://minecraft.wiki/w/Armor
You would need to use some algebra to approximate the full damage taken. Unfortunate part is the formula is not one-to-one, and I expect EntityHurt to lose some precision with the damage received.
I guess my next best bet is it just replace all the default armor with 0 points varients?
all I know is that bedrock has weird damage calculation in general
this is most noticable with weakness effect
for whatever reason, having weakness effect and any damage bonus enchantment clamps the value of minimum base attack damage to 0
so that the damage bonus enchantments can still apply damage (since they should be unaffected by weakness)
so yeah, youd lose a lot of precision like what sprunkles said if you follow wiki formula since there are a lot of stuff under the hood
So taking raw values would be easier?
because I have 2 options for creating my own damage system
- Reverse engineer damage calcs
- Remove all instances of the vanilla armor system and replace them with custom items
id go for the latter
it would be less headache
Fair
I just need to find a way for healing to not trigger entity hurt somehow
Because it does for whatever reason
healing triggers... what?
😭
are you sure thats entityhurt and not entityhealthchanged event?
100% sure
what a bugrock moment
reminds me of an instance where you can deal negative damage with spear charge which heals mobs
is it possible to listen for errors from the packet rate limit config for BDS with script API? like these ones pictured below:
You can create a BDS loader and listen to output of a process, then send information via scriptevent.
Anyone who knows the Custom Block Components via Script API.. does anyone know why the onPlayerBreak doesn't let me get the final "block_state"? I'm simply just using console.warn(brokenBlockPermutation.getState(params.growth_state)); and it gets all states from 0-6 but will not get 7.
My block states: json "states": { "mistvale:growth": [0, 1, 2, 3, 4, 5, 6, 7] }
Each state exists and will grow to state 7 but when I try to log it, it simply just wont find it.
Going to need more context, what does it return? Any content log? What are you tryin to acheive.
Literally returns nothing... I just want to give a player an item when they break the block at it's final state.
Open a post with your block code and script.
Whoops thanks, I use lots of languages and get forgetful, I'm using python a lot atm. Yes labels or a for loop then.
Anyone good at scripting that can help mod my one piece add on for my realm with custom swords and fruits and stuff
On bedrock
In custom commands how can i have second parameters for first parameters, like /cmd parameter1 parameter2
found some of my old code so im here to jump scare everyone
I updated my local server and the addons aren't working. The manifest specifies @minecraft/server, but it's not recognizing the module.
show ur manifest
{
"format_version": 2,
"metadata": {
"authors": [
"LukaCloud"
],
"generated_with": {
"bridge": [
"2.7.51"
],
"dash": [
"0.11.7"
]
}
},
"header": {
"name": "Extra Content for Serp",
"description": "Addon criada por LukaCloud",
"min_engine_version": [
1,
21,
90
],
"uuid": "4078b19e-7cf9-415e-a2be-8774edd1b1a1",
"version": [
1,
0,
0
]
},
"modules": [
{
"type": "data",
"uuid": "cb246454-990e-4045-b10f-2e485db3729d",
"version": [
1,
0,
0
]
},
{
"type": "script",
"language": "javascript",
"uuid": "15f6d805-6fc7-4ad1-934c-dd1515933522",
"entry": "scripts/main.js",
"version": [
1,
0,
0
]
}
],
"dependencies": [
{
"uuid": "24fda533-a246-4148-9bb3-6116ac36956f",
"version": [
1,
0,
0
]
},
{
"module_name": "@minecraft/server",
"version": "beta"
},
{
"module_name": "@minecraft/server-ui",
"version": "2.1.0-beta"
},
{
"module_name": "@minecraft/server-net",
"version": "1.0.0-beta"
}
]
}
er
heres mine if u wanna copy
{
"format_version": 2,
"header": {
"name": "Quality of Life",
"min_engine_version": [1, 20, 20],
"uuid": "24905328-cfcd-4537-a7d1-9dce930c135d",
"description": "Made by Osuea",
"version": [2, 0, 0]
},
"modules": [
{
"type": "script",
"language": "javascript",
"entry": "scripts/index.js",
"uuid": "275d9f53-e7e0-4f87-bbc3-ed894198515e",
"version": [2, 0, 0]
}
],
"dependencies": [
{
"module_name": "@minecraft/server",
"version": "2.4.0-beta"
},
{
"module_name": "@minecraft/server-admin",
"version": "1.0.0-beta"
},
{
"module_name": "@minecraft/server-ui",
"version": "2.1.0-beta"
}
]
}
Ah, this beta is due to the new version of Minecraft.
i started using just "beta"
why is this yelling at me TwT
Wrong types inside a library, I recommend overriding them or simply add // @ts-ignore line above.
ty
wdymmmmm
its mojangles
Is the camera animations still in preview or is it in the beta api?
spline?
yeah
beta
are the typings just all sorts of messed up?
And you are using this as a your font for coding… duh.
Sometimes, they are.
i confused myself, its currently in minecraft preview correct?
ye
its for pos only
tbh I dont care too much for the rotation
it is really cool
I just want a curve between points lol
I mean technically I could make a system for that
but its being added so no point ill just wait lol
im making a gamestart command for a certain tag so i want it to be a 10% chance you get this tag and if you dont then you just dont
Is there a way to display items like entities? Like when they are dropped but without being able to pick them up and without having to make 100 entities
guys is there any way to get the weapon damage using script
sadly no
🙁
is there anyway to make this script have a tag and level required at the same time?
{
"format_version":"1.16.100",
"animation_controllers":{
"controller.animation.h_haki":{
"states":{
"default":{
"transitions":[
// Level 1 or above with learning Conqueror's Haki 1
{"h_haki_1":"q.property('op_asa:h_haki')<1 && q.tag >= "Hao""},
// Level 50 or above with learning Conqueror's Haki 2
{"h_haki_2":"q.property('op_asa:h_haki')<2 && q.player_level >= 50"},
// Level 100 or above with learning Conqueror's Haki 3
{"h_haki_3":"q.property('op_asa:h_haki')<3 && q.player_level >= 100"},
// Already learned Conqueror's Haki 1, below level 1
{"h_haki_1_lost":"q.property('op_asa:h_haki')>=1 && q.player_level < 1"},
// Already learned Conqueror's Haki 2, below level 50
{"h_haki_2_lost":"q.property('op_asa:h_haki')>=2 && q.player_level < 50"},
// Already learned Conqueror's Haki 3, below level 100
{"h_haki_3_lost":"q.property('op_asa:h_haki')>=3 && q.player_level < 100"}
]
},
@woven loomcan you help me rq with this script
#1067869022273667152 next time
ok my apologies midn helping tho?
were villager's Initialization cause always "Event" when they spawned in villages?
iron golems too
it sucks because you cant check if an iron golem spawns from a player or in a village naturally.
Does iron golem still do Event?
I reckon that makes sense since an event triggered from being built. Does other golems and the Wither do the same?
iron golem returns "Event" when spawning from built, yeah
ill check if the others do the same
no, snow golems return "Spawned"
Wither aswell
Can I get ItemStack to not account for durability because I'm trying to use container.contains() and container.find(), but they don't return the item simply because the durability being damaged
whats AABB? the doc says its an entity's collision bounds, what exactly is it?
idk so i had to search https://stackoverflow.com/questions/22512319/what-is-aabb-collision-detection
i know its an Axis Aligned Bounding Box, i just want to know how it behaves in bedrock
im assuming its simply for collision, but considering how you can adjust collision for entities...
you can adjust collision for entities...
You can do that real-time?
By using component groups.
hey @round bone can you help me with this js
QuestSystem.executeQuest(killer, 'Wheat', deadEntity.typeId);
but this system is for collect wheat but has the functions of detecting if a entity died for another quest that im trying t change
- Do not ping people, if they don't have @ in their nickname.
-# I don't want to be mean, just don't ping me next time. - You provided me only one line of code. Bring more context, to resolve an issue.
one of the meaner ways to put it
I know, but it's a perfect example of how not to ask other people for help.
Simply post it, wait for reply, rely on AI/Cursor IDE if you still didn't get any answer.
I just found it funny that you said you didnt want to be mean but you did that, thats all
i totally get it, I dont want people pinging me neither
-# i wouldnt have expressed it like that though
ok
so these are different quest like Kaiozku,Kaizoku2 and now im trying to make a wheat quest
prefferably a post pls
ok
guys does anyone know the equivalent of .addEffect and .applyImpulse in V2?
i get the error not a function when using these
huh? it still exists in v2
i got it for this player.addEffect("resistance", 10);
are you sure the error is from there?
the content log referenced this line
mkay
import { system, world, Entity, Player } from '@minecraft/server'
world.afterEvents.itemUse.subscribe(({ source, itemStack }) => {
if (itemStack.typeId === "redstone:infused_copper_shard") {
const player = Player;
player.addEffect("resistance", 10);
}
});```
oh
...
when you done can you help me void
i feel like you wanted to check if the source is player
use source from the event.
yeah
world.afterEvents.itemUse.subscribe(({ source: player, itemStack }) => {
if (itemStack.typeId === "redstone:infused_copper_shard") {
player.addEffect("resistance", 10);
}
});
here
there
you dont have to check for type
since player is the only thing that can use items
or at least fire that event
mkay
thanks guys
oh and one more thing
is this correct?
entity.applyImpulse({ x: 0, y: 0.8, z: 0 });
yes
applyImpulse() takes Vector3 as argument
so yes you put a Vector3 in there
it is correct
sorry for bothering again but uh
const heldItem = inventory.getItem(damagingEntity.selectedSlot);
i think i did something wrong on this line
selectedSlotIndex
ima try that thanks 🙂
works for me.
if you are using afterEvents, it wont trigger if the entity does not have the interact component.
Oh
let me try thank you
does playAnimation work on entitties
yes
will setting to loop:true at the aniamtion file work or will i need to do runInterval such as if i tried to make it run walk animation
well, the event wont trigger in all contexts of when the interaction is not successful
so it can also trigger from feeding an animal if it has the tamable component, even without the interact component
im not sure, ive never really used the method for anything.
Ok its not working..
The console warn is not showing, I'm constantly right-clicking the creeper, but nope
try it with a flint and steel on hand
maybe afterevents?
I tried both afterEvents and beforeEvents
I also tried latest beta and stable
huh
this is being spooky whattt
I made sure the script is working and loaded too,
Oh 1 sec
Uhh it's now working nvm
But it wasn't working on stable..Still thats werid... I forgot to turn on Beta API, but now it works after turning it on
Does anyone know why my item isn't cleared from my inventory using setItem in a system.run()? It fails to run if it's not done like this due to not having required privileges but then the item can't seem to clear until I try to use the item again from which it then clears as if it's not updating the inventory when it should.
system.run(() => {
inventory.setItem(selectedSlot, new ItemStack('minecraft:air'));
block.setPermutation(
BlockPermutation.resolve('minecraft:lit_furnace', {
'minecraft:cardinal_direction': facing,
})
);
furnaceTimer = dimension.spawnEntity('mistvale:hologram', {
x: location.x + hologramOffset.x,
y: location.y + hologramOffset.y,
z: location.z + hologramOffset.z,
});
furnaceTimer.nameTag = `§e${furnaceTime}`;
});```
This is part of my code from which you can see how I'm clearing it. Is this an issue on my end or did this become a bug in the recent updates?
not really related but you can just do
setItem(Slot)
if the second argument is undefined, the function will clear the slot
Weirdly enough.. I think that fixed it 😭
How strange... Bugrock at its finest
or you cannot make a itemstack with the id air
maybe
well it works on second interaction and it would still be setting air 
either way it's fixed now 
🤷♂️ just a guess
maybe
[a ghost stack](#1404868530037330032 message)
its because the value is by default undefined, so you can exclude it. thats a js thing
function f(a,b) {
console.log(a,b);
}
f(); //both undefined
f(5); //b undefined
does anyone have a good idea for a first project with javascript basics
Anyone know what/why this error is happening and why mc freezes when opening a world with this?
hey void
something nothing to do with the script api. idk something like a command line tool
gonna ask you can you help me fix a script but ok]
sure I can
here's their post https://discord.com/channels/523663022053392405/1434892923840892989
for some reason this still isnt working
mc.world.afterEvents.itemUse.subscribe((e) =>{
const {source, itemStack} = e;
if (itemStack.typeId == "minecraft:bundle") {
let container = itemStack.getComponent("inventory").container;
let containerItem = container.firstEmptySlot();
mc.world.sendMessage(containerItem.typeId);
source.sendMessage(`used ${itemStack.typeId}`);
}
})
why can't I get the inventory component of bundles now?
what changed?
getComponents even return 0 components for the bundle at all
what the heck changed
did you enable beta apis in your world?
WAIT THATS IN BETA?
yeah, i just checked
What’s up here?
if (id.includes("cake")) {
const bite = SS_CAKE_BITE[index];
if (bite === undefined) {
player.sendMessage("§cSS not applicable for cake.");
return;
}
await world.getDimension(player.dimension.id).runCommand(
`setblock ${x} ${y} ${z} minecraft:cake[“bite_counter”=${bite}] replace`
);
player.sendMessage(`§aSet cake bite_counter=${bite} (SS${index}).`);
return;
}
Error:
[Scripting][warning]-[canopy:ss] error: CommandError: Error occurred with parsing command params: Syntax error: Unexpected '“bite_counter”': at 'raft:cake[>>“bite_counter”<<=6] replac'
The normal setblock command for reference
/setblock ~~~ cake[“bite_counter”=6]
I don’t quite understand
is the quotes required?
oh lol
it's the quotes]
“bite_counter” and "bite_counter" are not the same
look at the quotes
try it
"bite counter"
not “bite_counter”
Ohhhhh
disables smart quotes
yep that works (it also needed that _)
i need help
If I want to get better at making scripts, should I try to focus more on learning OOP?
Since from what I've seen, most stuff when I used to do scripts were mainly object related stuff
Idk if that's changed since for add-ons as I haven't coded in a lot of months
i think OOP matters especially on large scaled scripts
for small scaled projects, it shouldnt be a biggie
I want to re-make and update my framed blocks add-on and I think I'll want to learn more OOP for doing so
I had a great database code for it, but the rest of it was kinda bad, even though it was very performative
yeah if you think its bad on maintenance side, go for it
There was some errors for people that they reported some textures wouldn't show up for them. It worked for me and a friend, but would randomly not show for others
odd
Which I still don't know what the problem was
how does the framed blocks work?
It uses a lot of permutations across many different blocks. Each block would have like 16 permutations per, and when you clicked on a framed block with a block, it would then change to that texture
I had to make it a lot of blocks otherwise there would be too much data in each block
sounds like a desync on rp side then
And when I tried to do it with the blocks.json file for the state related texture changes, it wouldn't do any textures if the block had 2 different states. So it had to be 1 state type per block 1-16
Hm
i honeslty barely worked with blocks to understand much about this
so i cant really make clear answers
https://jaylydev.github.io/scriptapi-docs/preview/index.html where are the npm types
@somber cedar /docs info in #debug-playground
Installation for @minecraft/server
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
Is it possible right now to setLore an item without doing "inventory.setItem"?
containerslot
What is setitemlorefunction
Nice, thank you @somber cedar
Something i wanted to do was a way to randomly pick an item from any in the game but there’s like no current good way to do that I can work out
Hm, interesting
hello, in the new version how create custom command ?
import { Player, world, system, CommandPermissionLevel, CustomCommandParamType} from "@minecraft/server"
system.beforeEvents.watchdogTerminate.subscribe((init) => {
init.customCommandRegistry.registerCommand(showPlayerCommand, showPlayer);
})
export const showPlayerCommand = {
name: "lu:showPlayer",
description: "<target: string> -> print target: Player",
permissionLevel: 1,
cheatsRequired: true,
optionalParameters: [{ type: CustomCommandParamType.EntitySelector, name: "Pseudo"}]
}
export function showPlayer(result: string, player: Player) {
let allPlayers: Player[] = world.getAllPlayers()
// const target = allPlayers.find((result.sourceEntity))
player.msg(result)
}
I have this but doens't work why?
thats wrong
its startUp
not watchdogTerminate
yeah but what is the error
try running npm i --save-dev @minecraft/[email protected]@1.21.120-stable
Property 'startUp' does not exist on type 'SystemBeforeEvents'.ts(2339)
Module '"@minecraft/server"' has no exported member 'CustomCommandParamType'.ts(2305)
correct npm command ^
just update the node package to the latest beta version
also it's startup not startUp https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.SystemBeforeEvents.html#startup
damn effcetively, I am stupid thank you
jayly docs search bar help me a lot
why ?
search 'custom command' in that docs and click on those examples
system.beforeEvents.startup.subscribe((init: StartupEvent) => {
const helloCommand: CustomCommand = {
name: "creator:hellocustomcommand",
description: "Celebration super party hello",
permissionLevel: CommandPermissionLevel.Any,
optionalParameters: [{ type: CustomCommandParamType.Integer, name: "celebrationSize" }],
};
init.customCommandRegistry.registerCommand(helloCommand, helloCustomCommand);
});
function helloCustomCommand(origin: CustomCommandOrigin, celebrationSize?: number): CustomCommandResult {
it should look something like this (check here)
import { world } from "@minecraft/server";
const carryingMap = new Map();
world.events.beforeChat.subscribe((event) => {
const player = event.sender;
console.log(`[DEBUG] Chat detected from ${player.name}: "${event.message}"`); // debug log
// Cancel all chat for testing
event.cancel = true;
const message = event.message.trim().toLowerCase();
if (message === "!carry") {
console.log(`[DEBUG] !carry triggered by ${player.name}`);
// check tag
if (player.hasTag("devil")) {
player.runCommand(`tellraw @s {"rawtext":[{"text":"You can't carry a devil fruit user!"}]}`);
return;
}
// find nearby devil fruit user
const nearby = world.getPlayers({ location: player.location, maxDistance: 3 });
let found = false;
for (const p of nearby) {
if (p.hasTag("devil") && !Array.from(carryingMap.values()).includes(p)) {
found = true;
carryingMap.set(player, p);
player.runCommand(`tellraw @s {"rawtext":[{"text":"You are now carrying ${p.name}!"}]}`);
p.runCommand(`tellraw @s {"rawtext":[{"text":"You are being carried by ${player.name}!"}]}`);
break;
}
}
if (!found) player.runCommand(`tellraw @s {"rawtext":[{"text":"No devil fruit users nearby!"}]}`);
}
if (message === "!release") {
if (carryingMap.has(player)) {
const p = carryingMap.get(player);
carryingMap.delete(player);
player.runCommand(`tellraw @s {"rawtext":[{"text":"You released ${p.name}."}]}`);
p.runCommand(`tellraw @s {"rawtext":[{"text":"You were released by ${player.name}."}]}`);
} else {
player.runCommand(`tellraw @s {"rawtext":[{"text":"You are not carrying anyone!"}]}`);
}
}
});
everytime i type in chat !carry it dont even give me the message that if (!found) player.runCommand(tellraw @s {"rawtext":[{"text":"No devil fruit users nearby!"}]}); can anyone help me fix this
Debug result for [code](#1067535608660107284 message)
Compiler found 1 errors:
[36m<REPL0>.js[0m:[33m5[0m:[33m7[0m - [31merror[0m[30m TS2339: [0mProperty 'events' does not exist on type 'World'.
[7m5[0m world.events.beforeChat.subscribe((event) => {
[7m [0m [31m ~~~~~~[0m
There are no errors from ESLint.
beforeChat moved to chatSend
or use custom commands api
Documentation for Script API - v1.21.120 (Beta APIs) | A set of events that fire before an actual action occurs. In most cases, you can potentially cancel or modify the impending event. Note that in before events any APIs that modify gameplay state will not function and will throw an error. (e.g., dimension.spawnEntity)
so remove before and put chatSend @somber cedar @somber cedar
ye bc i just fixed that and its still not triggering once i say !carry
its weird theres no problems in game so idk why its acting weird
debug time
...
we don't do jokes here
you debug
procedural codes leads to procedural bugs
you backtrack
remove each code 1 by 1
kind of like losing something and you backtracking the path that you took
we still don't have dynamic subcommands for custom commands yet, right?
Not yet, sadly.
Any Android devs here? I've recently switched to Acode from .bridge as .bridge was giving me errors all of the time. Is there any way to get autocompletions for the scripting API in Acode?
I'll check it out, thanks. Also, are .json autocompletions possible too?
dont know
Do we have any ideas about manifest setting rollout?
Elaborate.
Sorry, so with manifest v3, there's settings, and I'd really like to use them in scripting to change things without custom commands or UI. I know it's in preview 1.21.110+ but I assumed it would be getting close to going public soon. Not sure if they were also thinking of adding settings accessibility in Molang for RP access
Pack settings are readable via scripting and molang yes.
They are in preview only I believe still, I could be wrong, but I reckon .130 will be the official "tada" moment.
That'd be awesome, so maybe with the next drop it'll be available in beta?
No experiments needed to my knowledge.
Thanks!
Hm, so just "beta" isn't working on bds?
I was facing the same issue and I'm wondering
I've already solved my problem.
For some reason, add-ons don't work on local BDS, at least not on my computer.
I'm using a host now.
So it wasn't the "beta" as version which caused the issue?
Which seems weird because it also doesn't recognize my other addons using stable versions
Have you updated? I'm using that on BDS
Yes, just downloaded it like a few minutes ago
Maybe I didn't update correctly, I will try my addons on a fresh installation
How can I change a players skin depending on an entity event or like multiple
is there a method to shoot entities? or do you just spawn it and apply impulse?
I would do it that way.
If the entity is a projectile (it has the "minecraft:projectile" component) then you could acquire the Projectile component and use the shoot() method
Is there a way to set an entities component group through scripting
.triggerEvent() method?
Would work in most cases but the event in this case has a 50/50 chance of adding the component group I want.
wouldnt it still work?
cuz youre technically triggering event
But the event is using randomize: []
I need it so when I use a specific item on the mob it'll 100% of the time active the comp group
then you might need another event
Basically the mob has a 50/50 chance of ageing into 1 of 2 variants. The item being used on it will pick a variant based on which item I use
Probably will do. I'm surprised there isn't a method for straight up adding/removing comp groups yet
well component groups need events to be set anyway
It would help with editing things like zombification of villagers as I'm sure that uses randomize: [] in the become_zombie event. That way you don't have to make edits to the villager.json
Just an example
oh you meant that
I mean generally. Some vanilla mobs use randomize in the event. So if people want to add comp groups to vanilla mobs,. they'd have to edit the .JSON directly to add new events
yeah true
Hopefully one day we get a method for adding/removing comp groups directly without triggering events
import { MinecraftBlockTypes, MinecraftItemTypes } from "@minecraft/vanilla-data";
How do I use the vanilla data module? I want to use its data types in my code.
Can someone please help me?
You'll have to bundle it. I did just make a guide a few days ago on how to do that: #1431675871806361733 message
tankyou
I would like to see if you find my guide easy to read. I've tried to make it understandable, but I am the one who wrote it, so I can't tell reading it myself.
Have a read and tell me what you think.
Hey, is there a way to solve the privilege problems once and for all?
how would I make it so the player's armor went invisible along with the player
i think using system.run would sove it
world shutdown event doesnt work? whys it in the docs
or am i just using it wrong cuz it says the event doesnt exist according to the logs
It's system https://stirante.com/script/server/2.5.0-beta.1.21.130-preview.24/classes/SystemBeforeEvents.html#shutdown
Documentation for @minecraft/server
Yes, but do you know if a solution exists to solve this problem every time it is not put system.run every time
how does the /locate command work internally and is it possible to recreate it?
is it possible to remove a items nametag, so I can then list the item as the typeId instead of the changed nametag on the item
in your RP>texts>en_US.lang if you remove the one for your item i think it defaults to the typeId
I meant could I make a items nametag undefined like item.nameTag = undefined would doing that make it revert to the typeId without a nametag
i think litterly just deleting it does that because just while making stuff ive messed up where it dosent identify it right and when looking at the item it has its name as dp:ninja_helmet for exmaple
https://feedback.minecraft.net/hc/en-us/articles/40566672351885-Minecraft-1-21-120-Bedrock
Does this mean chatSend can consistently work now?
Basically, from what I can tell - if someone turns on beta API in a world now, it's not likely to break unless chatSend is majorly changed.
This "beta" automatically choosing the latest compatible beta version, it skips the need to fix the beta number. Since before - each major update of Minecraft, a new version of the add-on had to be released with the right beta number (or, you had to manually edit the manifest file in your files)
But now - that problem should be gone
It can, unless there's an API change
alright thanksss
what channek do i go to for type script
here
How can I make it so when something spawns in it's instantly tamed
oh hello would u like to assist me?
get the tameable component.
the spawn entity method returns the entity being spawned
Documentation for @minecraft/server
Don't ask to ask, just send your question.
is there away to get the max value of a property?
getProperty and setProperty exist but is there like a method to get the max value?
function getMaxProperty(entity, propertyName) {
let i = 0
try {
for (; ; i++) {
entity.setProperty(propertyName, i);
}
} catch {
return i - 1;
}
}
``` Ik its a ugly code but I did it like this
it's a bit weird but if you try to set the property to a very high value that would never be valid it will throw an error with the max value
let max;
try {
entity.setProperty("my:prop", 1000000);
} catch (e) {
max = e.maxValue;
}
oh thats better thanks
how did you know that maxValue exist? Like I want to understand it
Oh nvm
export class ArgumentOutOfBoundsError extends Error {
private constructor();
/**
* @remarks
* Max expected value for the condition.
*
*/
maxValue: number;
/**
* @remarks
* Min expected value for the condition.
*
*/
minValue: number;
/**
* @remarks
* Passed-in value for the argument.
*
*/
value: number;
}
I found it
Also documented here
https://jaylydev.github.io/scriptapi-docs/features/dynamic-properties.html
Warning
There is a length limit of 32,767 bytes for string dynamic properties.
Edit: not sure about other types like Int just realized that might be what you are asking
Actually found it as well lmfao
The numeric value must be a signed 64-bit float, ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (inclusive).
just wandering, if I summon a SimulatedPlayer into an aternos server, would it count as if someone is connected?
the idea just popped in my head and i got curious
are there some ideas to supporting Uint8Array?
With dedicated servers, if I have a console.log in a script, will it output to the server's console?
hmm
How do you store a data inside an item using scripts?
Like per item it would be a diffrent data too
Dynamic property or smth thats what i remember
ye
Recording this for future searches, because when I looked, not much info on dimension.getTopmostBlock(me.location) and it is not explained anywhere I can find.
I was looking for a way to figure out if a player is outside. I decided to try getTopmostBlock and maybe thought I needed getBlockFromRayCast too.... I honestly thought it would return the top block above the location given, but in testing I found it was giving me the block I was standing on. But that is not the end, I was standing under a tree, so it seems that it most likely gives you the top solid block . I stood under a web, under the leaves and got the block below me. I took a few blocks out of the tree trunk, stood under it and got the top block as log. That is the full extent of my testing.. under water not done, as it was not pertinent to my needs, but would be good to know if top of water or ocean floor... Not sure how end or nether work with this. nether probably not so much cause of the bedrock roof.
So I surmised, if the y-axis of top block returned <= me.location.y then, I am for sure outside. That is the quick and dirty of it, I will need to test a 3x3 grid around me if the topBlock.typeId.includes('log'). Not sure I can do much more than that.
If anyone else had to know that info, what other way is there to get it?
...in other findings... block.getSkyLightLevel() works horrible with the shadows and stuff. My player shdow thru it off. I figured out how to turn all that stuff of, so works better now. I think it should take into account sunlight from neighboring blocks, as sunrays do spread...
That's not what it's getting.
Yes it gets the solid block. it is just like get block from raycast.
Can you expand on that? If I gave a location at my head, why do I get the block below my feet?
I used ray cast to determine there were leaves above my head, nothing but leaves to the sky.
That message is referring to skylight.
getTopMostBlock works exactly like a raycast. So by default it ignores transparent blocks.
The skylight confused me... I looked up and there was the sun, right over my head and I look down and there was a part shadow me and skylight was 0. I could not get it to work until I turned off all that shadow nonsense.
As in, there is a direct path from the block you were on to the sky?
Yes
Sky light level isnt based on the suns position, its like a raycast downwards.
I figured that it would not be based on that... but the fact that it was right overhead... maybe cause it made the shadow bigger or something. I was only playing with it cause I wanted to try all the options to figure out what to use... but getTopmostBlock works well, so I do not have to care about skylight... until I do....
I was in a dark forest.. so getting a sky view was not that easy.... LOL
Is custom component that is made in one pack can be use on other pack?
how to test my script here?
Please select an option you have problem with
Suggestion for @broken pawn
Description
This README is auto generated, Edit the README so that users know what this package does.
Credits
These scripts were written by Jayly
Installation for @minecraft/server-ui
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
Does anyone know if something's wrong in this line?
world.beforeEvents.blockBreak.subscribe((event) => { const { block, player } = event;
is there anyway to make wheat automatically plant seed and grow back once you destroy it
blockbreak isnt a beforeevent
hey uhh
i redid the code but the game still throws errors on this line
world.afterEvents.blockBreak.subscribe(({ source: block, player, brokenBlockPermutation }) => {
oh wait
i think i see the problem
also im trying to make it so if a player has hakia ctivated which is busoshoku_on event and kill a mob it gives him xp am i doing something wrong?
'''js
world.events.entityHurt.subscribe(({damageSource, hurtEntity}) => {
// Make sure the source is a player
const player = damageSource?.damagingEntity;
if(player && player.typeId === "minecraft:player"){
// Check if Busoshoku is active
if(player.getProperty("busoshoku_on")){
const hakiExp = player.getProperty("op_asa:b_haki_exp");
if(hakiExp < 50){
player.setProperty("op_asa:b_haki_exp", hakiExp + 1);
// First acquisition
if(hakiExp === 0){
player.setProperty("op_asa:b_haki",1);
player.playSound("random.levelup");
player.sendMessage({rawtext:[{translate:"rawtext.b_haki_1.acquired"}]});
}
// Level up every 10 exp
else if(hakiExp % 10 === 9){
player.playSound("random.levelup");
player.sendMessage({rawtext:[{translate:"rawtext.b_haki_1.levelup"}]});
}
// Normal EXP gain
else{
player.playSound("random.orb");
player.sendMessage({rawtext:[{translate:"rawtext.b_haki_1.exp"}]});
}
}
else{
// Max level reached
player.sendMessage({rawtext:[{translate:"rawtext.b_haki_1.levelmax"}]});
}
}
}
'''
For future, it is 3 back ticks (key to left of 1), not 3 single quotes to make the code bocks.
I made a few changes to avoid error, if the player.json is messed with or overwritten by another pack. It is all noted with FIXME: or TODO: or REFACTORED: or ADDED```js
world.afterEvents.entityHurt.subscribe(({ damageSource, hurtEntity }) => {
// Make sure the source is a player
const player = damageSource?.damagingEntity;
if (!player || !(player instanceof Player)) return; //REFACTORED:
// Check if Busoshoku is active
//REFACTORED: to avoid error if player json is messed with
const busoshoku_on = player.getProperty("busoshoku_on"); //FIXME: name space on property ???
if (!busoshoku_on || typeof busoshoku_on !== 'boolean') return;
if (busoshoku_on) {
const hakiExp = player.getProperty("op_asa:b_haki_exp");
if (typeof hakiExp !== 'number') return; // ADDED
if (hakiExp < 50) {
player.setProperty("op_asa:b_haki_exp", hakiExp + 1);
// First acquisition
if (hakiExp === 0) {
player.setProperty("op_asa:b_haki", 1); //FIXME: name is not the same as above
player.playSound("random.levelup");
player.sendMessage({ rawtext: [ { translate: "rawtext.b_haki_1.acquired" } ] });
}
// Level up every 10 exp
else if (hakiExp % 10 === 9) {
player.playSound("random.levelup");
player.sendMessage({ rawtext: [ { translate: "rawtext.b_haki_1.levelup" } ] });
//TODO: add the random level up code
}
// Normal EXP gain
else {
player.playSound("random.orb");
player.sendMessage({ rawtext: [ { translate: "rawtext.b_haki_1.exp" } ] });
//TODO: add the code to give random orb
}
}
else {
// Max level reached
player.sendMessage({ rawtext: [ { translate: "rawtext.b_haki_1.levelmax" } ] });
}
}
});```
I had to add a ) at the end, so not sure who was missing what
What was the error you are getting? I would assume it the 2 FIXME:s, the property names.
and you might want to build your reusable class for checking validity of property names and types before using them.
If using vscode, there is a certain ext that makes TODO: and FIXME: highlight in your code
If you want to cut down on the possibility of your player.json being suppressed, then move how this works to dynamic variables and try not to have anything in the palyer.json. I believe with all that they give, this may be possible.. depending
ew
hey, someone would have a databse.ts file that works because I can’t find it anymore even the con-databse doesn’t seem to work from my side
how to detect when you shoot a crossbow?

Nope
Cant detect shooting crossbow with that
Can you just drop the correct answer, instead calling claiming that I am wrong?
perhaps PlayerInventoryItemChangeAfterEvent #1436922644481048710 message
Isn't there smth like an instant shot, where these events also apply?
😅
Looks like a new Discord update
Idk too
I tried ingams
I remember that I used once one of the events that I have said earlier for detecting a crossbow shooting and it was all fine
what’s the use of startUp event?
register components or custom commands
Can a custom component be used at different pack?
Is there a way to /reload one js file?
why do I get this error when I dont have op
customCommandRegistry.registerCommand({
name: "ct:pay",
description: "Pay another player some coins",
permissionLevel: CommandPermissionLevel.Any,
mandatoryParameters: [
{
name: "target_player",
type: CustomCommandParamType.PlayerSelector,
},
{
name: "amount",
type: CustomCommandParamType.Integer,
}
]
}
do I need to set cheatsRequired false?
or how do I fix this permission error
you need to set required permission
its set to operator by default iirc
@weary umbra
oh wait
the permission level is there
yeah Ik thats so weird I think its a bug
But cheats are on
whar
actually wait
if the cheats are needed, then it should print a yellow message saying "cheats are required for this command" or something
but thats a different one
is the function wrapped in system.run()?
yeah I uses console.warn to see if something returns and it doesnt give me anything its an issue with the command
odd
when we could make custom commands without namespaces?
since the beginning of custom commands
how
it wasnt possible until the next update which allowed typing out commands without namespace if there was no other commands with the same command name
in which version?
but the next update made it so that this is the case
custom commands have to have a namespace
the game will automatically register an alias without a namespace if no other commands with the name exist
did you put your rp/bp in the shared folder or in the random number folder
or It might be that your files are gone. It happend to alot of people bc of the new update
yeah than move your rp/bp into the shared folder
Is there any way to make it so it tames when the entity spawns itself not the player
import { world } from "@minecraft/server";
world.afterEvents.playerSpawn.subscribe(({ player }) => {
const wolf = player.dimension.spawnEntity("minecraft:wolf", player.location);
// Tame the wolf to the player
const tameable = wolf.getComponent("minecraft:tameable");
tameable.tame(player);
});```
wdym "itself not the player"?
I want the entity to tame when the entity spawns in not when the player spawns in
you can use entitySpawn event
you just need a way to specify which player to be the tamer
If anyone has any experience with using the typescript project setup... Does anyone know why my other files aren't being pushed to my pack?
-# https://github.com/microsoft/minecraft-scripting-samples/tree/main/ts-starter
Ah, it seems to be made to just merge all files to main.js for some reason.
Very strange...
yeah, thats basically how TS works for scripting
Speaking of (sorry to piggyback here) but anyway to check tamed player for entity types? I was seeing some mobs do have this in scripting APIs Tameable and TameMount but others like wolves only have isTamed which is Boolean so no way to see which player a tamed wolf is owned by?
Trying to determine all a players "pets" or tamed mobs within a given radius around the player
doesnt tameable component have tamedToPlayer?: Player property?
Tameable does but I did not see this available on tamed wolves sadly 🥲 unless I am missing something which could very well be likely
its probably the best to double check
it doesnt make sense for wolves to not have it...
Will make a post after testing if still having issues for more help and see if better document since I was trying to search here too
the tameable component on wolves will return undefined once you tame them.
oh
its just how the file it setup.
OH. ok that explains
the tameable component gets removed afterwards
so you cant get it in scripts
its pretty annoying.
and obviously editing the wolf file just to be able to do it is not ideal
i feel like this is not intended
cuz, theres tamedToPlayer
but it stops existing because the tameable component would be gone
seems like a simple fix.
buut i think its not on the top priority rn
the tameable component is in the wolf_wild component group
and that gets removed after being tamed ofc.
Yeah I am seeing how terrible looks like still limitations on API for now and not enough people complaining with scripting APIs for mojang to care to add this in the isTamed component
There has to be something in game files to know who the player is tamed to for wolf since clearly the wolves know their owner in native gameplay
#1278599406173683784 message
theres also an issue where tamed wolves ignore damages done by applyDamage with damagingEntity set to the owner
its quite messy
issues upon issues...
Like they just forgot about old ass mobs in APIs and only focus on new mobs 😢
#Bugrock moment
:pensib:
I understand priority and all but you are telling me 1 guy cant just fix this real quick
yeah some stuff do seem like a one line fix
okay to be fair, they fix bugs, im just a little annoyed
its not like they dont do anything about them
Lmfao nah just glad to know I'm not going crazy looking at docs and trying to debug my shit
Found that and unfortunately still an issue for now
like that bug where heart and hunger animations are sped up, including regeneration heart effect
they fixed the regeneration effect by making it slow
but kept the heart/hunger animation bug
exactly, thats what makes it infuriating
one little thing can ruin a creator's flow
and then you have to make some weird workaround, just like always
at least they fixed that one unmentioned bug where attacking with an item with damage bonus enchantment while having weakness effect clamping the base attack damage modifier
idk when they fixed that but it was quite critical to my addon
oh nice.
sobs in player.json
Entire feature in my addon I have to comment out for now due to API limitation since I can't reliably determine pet ownership of mobs and don't want to accidentally filter mobs close by to the player tamed to another player 🙃
I know how to fix the wolf thing Kent, so if you want to know my work around, ill let you know.
its pretty simple
do you know dynamic properties?
althrough this workaround wont work with wolves tamed before activating the addon.
Yes using this for addon settings per-played and globally but ideally would not want to have to set something that will require addon.
Unless you are saying add a per player dynamic prop on wolf or other entity when interacted like sit event etc that only owner can do?
Aka I don't want to only support wolves tamed after addon is added but previously tamed wolves too which I guess checking for something event like that and setting dynamic prop might work like that?
Unless you had totally different workaround lmfao
all you do is store a dynamic property of the owner's id on the wolf.
Yeah that is pretty much what I am targeting but also any native mobs tamed to the player to work with the addon
That could probably work yeah even if pet is tamed prior to using addon as long as the player interacts with the entity like sit event etc then can detect and set that?
Then use this to check for the owner
theres no way to check if you made the wolf sit or not though.
there's no event that triggers from the sittable component on the wolf
Gdi that kills that thought process haha
How to detect when a player is opening inventory?
trt interact with block event
how to detect interaction button/right click/hold screen of an item on js?
So after reading all of this what am i meant to do exactly
I think the final mention was basically that the only ability so far for certain entities such as wolves you have to use dynamic props on the entity and set the player's ID as a dynamic property for the wolf as the "owner" or whatever key you want.
This would only work for those mobs that were tamed with the addon enabled since you are adjusting the dynamic properties and especially placing the player ID as a value on the entity since that is not there natively.
But again only drawback only works for entities tamed with addon and not those without or prior to add-on so would not work for my case. Might be good for some other people though
From there though on your question as Seawhite mentioned the only question would be determining which player that entity should be tamed to on spawn.
And if you are only looking to set tamed on spawn and do not care about owner then the workaround using dynamic properties might not matter.
But if the player is spawning the entity with spawn egg should be able to detect on item use for spawn I think and player who spawned to tame to? But if natural spawn then you might have to get clever on how the tame on spawn logic would happen in your scripts
heya y'all
is it possible to disable the game from snowing in a certain area without editing the biome?
preferably with scripts only but i don't think it's possible with just scripts
You'll have to disable weather cycle.
Can i make it so that you can sleep in a bed at any time and it will skip to day and still do the animation or will i need to simulate it using scripting magic
Not possible but you can detect bed interactions using scripts, then just skip it to daytime
Thats what i ment by scripting magic i was just hoping to keep the sleep animation
Tho i might know a way assuming i can detect the time in a script
Yeah you can detect time using world.getTime()
you'll be able to re-create the camera animation using the camera APIs
Yeah and maybe some playanimation
Might do it a dif way if its day ill force to skip to night without animation if night skips to day without animation
Just cancel bed interactions and just do custom time skip animations using camera fade or something so it wont look as dry
I need to learn how to script camera animations
can i detect /me command with script api?
Do you want to disable it?
yes
If you're on BDS, disable a command via config.
Someone know of an alternative to event.cancel = true?
I didn't notice they removed it from hientity, and I want it to detect when an entity is hit without the entity receiving any damage or push.
entityHitEntity never had beforeEvent nor cancel
yea
is there a solution for that?
player.json
anyone got entity cloner
🥀
You can reimplement your own PVP system, but it takes a bit more time
I have done this thing in my project I was happy with result, so it depends on the scale of your addon/project
Is there any way to play walk animation on a simulated player?r
without moving?
Yea
I'm teleporting along the path and it's not playing any animations.
does sp support keep velocity?
no
how to set sky color to custom?
I guess the only option is to make a custom animation
i can play sneak animation tho
animation.player.sneaking
Movement animation uses the entity movement speed and math.sin
So just playing the animation does nothing
Ah yup makes sense
does applyImpulse work on players now in stable?
Yes, it sure does!
Yes
finally, thank you both for the info! that means I don't have to make a separate knockback and impulse
yes very
what are yall cooking?
it's wonky though
is still wonky? with the desyncs?
iirc its fixed?
or at least in preview
hmmmmm, I need to test that.
Why does my command not send a message even though I return a message?js return { message: `Setted nametag from §l${entities.map((entity) => entity.nameTag).join(", ")} §rto §l${nametag}`, status: Minecraft.CustomCommandStatus.Success }
try the command in command block and see how it goes
same problem
nothing?
import { ItemDurabilityComponent, ItemStack, world, EquipmentSlot, system, EntityMovementSkipComponent, Player, GameRule, World, Block, EnchantmentType, EnchantmentTypes, BlockVolumeBase, BlockLocationIterator, Entity, ItemLockMode, EntityDamageCause, System, TicksPerSecond, MolangVariableMap, StructureManager, PlatformType, Scoreboard, CommandPermissionLevel, CustomCommandParamType, CustomCommandOrigin
} from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
import { prefix } from "src/config";
import { getMainData } from "src/lib/database";
system.beforeEvents.startup.subscribe(({ customCommandRegistry }) => {
customCommandRegistry.registerCommand(
{
name: "cb:jobs",
description: "Ouvre un menu sur ses jobs ! ",
permissionLevel: CommandPermissionLevel.Any,
},
(origin) => {
const player = origin.sourceEntity as Player;
const data = getMainData(player);
let msg = `Imformation: `;
msg += `\nVoici vos niveaux de jobs : `;
msg += `\nMineur: ${data.mineurLevel}`;
msg += `\nFarmeur: ${data.farmeurLevel}`;
msg += `\nHunter: ${data.hunterLevel}`;
const form = new ActionFormData()
.title(prefix)
.body(msg)
.button(`Mineur\n(${data.mineurLevel})`)
.button(`Farmeur\n(${data.farmeurLevel})`)
.button(`Hunter\n(${data.hunterLevel})`)
.show(player).then(r => {
})
return { status: 0 };
}
);
});
hey, do you guys know why VS code highlights player in red?
Hi, I have a small problem with my game. It lags and stutters constantly, and I don't understand why. It's been like this since the last update. I've already uninstalled and reinstalled it, but it didn't work.
you can move your cursor above it so it will show you
the problem seems to be solved by itself, it is no longer present maybe a double import and therefore he was not happy at the level of the Player type
Does anyone have a calculation for determining the direction of the sun and moon to spawn a particle?
the problem has reappeared @dusky flicker
runCommandAsync is not a thing
Use regular runCommand method
ok but I don’t understand actually where to use runCommandAsync
Oh, I missed the code. Add // @ts-ignore above show
this is going to cause the conditions of ts to be ignored only for the next line?
Yes
It's pretty common type error while working with server-ui forms, other classes are also affected by it
😢
ok thank you for the clarification I will be for the next times
Pretty weird, but it's directly in library's code
I'm getting this error while updating components to v2. I have bumped the version number grater than 1.21.90 and regstered them with the new event. Any help pls 🙏
block json in question.
have you checked task manager while running?
also do you haveany pack running?
The processor shows 50%. And there are no packs.
Could someone provide an example of the PistonActivateAfterEvent class being used. I'm confused on how to use it to detect what block is being pushed and in what direction
Is there a way to update the armor durability without triggering the equip sound? 🤔
does setEquipment (or whatever youre using) play the sound event?
Yes, it plays "armor.equip_leather" I think
I tried using /stopsound but it doesn't work
that is weird ngl
why ask here though?
also could be the settings? have you changed it?
disable vv and lower render distance
I've already done all that.
welp go to official mojang discord or any technical server might be your hardware or softwares or a mumbo jumbo of stuff
you gotta find a lead
anyone on that can help me fix my script
Send a script and explain your problem then.
ok ty
i've created a post and @ u
dont ask to ask
is there a minecraft debugger video tutorial?
Is there a way to convert system.currentTick into an integer?
it is already an integer
Thank you
That gives me conformation that something else is wrong with my script 🥲
I'm error-less
I used console.warn to see what a variable reliant on currentTick said, and it just gave me Nan
My life was a big lie
Wondering if it's possible to make a JS UI that appears on pre-existing UI, like adding extra UI onto the crafting screen?
Or is that just possible with JSON?
There is nothing called JS UI
Probably, yes
I meant the UI you can make with Javascript
Nope
there isnt one
the one youre probably thinking of is server-ui, which is used to send 'forms'
can someone tell me why when I use herobrines chest ui the textures dont align with the correct images in the chest ui
Maybe ask herobrian
@valid ice ?
Are you using newest version of the pack?
Do you have custom items at all?
I got it from github so im pretty sure
im not using custom items no
Weird
I checked the textures on 1.21.120 and they all matched up
Which ones aren’t working for you?
well none of them seem to match at all?
Im using the spyglass that did not match plus other ones
Can you open a post and send your code
like how should I send it which file?
A question can only use 2 arguments.
.textField("Texto del mensaje:", "", mensajeActual.texto)
I'm using 3 and it gives me an error.
.textField('Label', 'Placeholder', { defaultValue: 'Default text' });
why does the world tick beore world load event is fired?
makes things so much harder
best destroyer method
why?
because i cant initialize states with it
new v2 changes means that if you want to have states in your addon they need to follow the world as those might need to access world data
but if you initialize them on world loaf its SLIGHTLY too late , as stuff can tick before that and you might need your state objects
wdym "states"?
any object that should hav its lifecycle synced with the world
Any examples?
And can u ping me when reply?
like a map of entities or simply some complex object that depends on world saved data
just very dumb that world load after fires after the first tick, negating its "setup" capabilities given stuff could tick right before it gets called and hence requiring suff to be initialized already. just makes code ugly requiring lazy on demand initialization instead and still refresh it on world load
I still don't quite understand... well, it doesn't matter
[Scripting][error]-ReferenceError: Native function [World::getPlayers] does not have required privileges. at enviarSiguiente (main.js:32)
at iniciarMensajes (main.js:40)
at <anonymous> (main.js:42)
[Scripting][error]-Plugin [§l§aSystema De bienvenida - 1.0.0] - [main.js] ran with error: [ReferenceError: Native function [World::getPlayers] does not have required privileges. at enviarSiguiente (main.js:32)
at iniciarMensajes (main.js:40)
at <anonymous> (main.js:42)
]
How can I prevent this? I want to save the data to avoid loss when closing a server, ro mundo, or realm.
Use system.run(() => { // code here })
how can I get the world seed?
You dont.
damm
Seems like a big hole in the API. Grabbing the seed could mean making PRNGs that are consistent across world instances
I'm doing that right now.
and it works but I need it to work dinamically in all worlds
ist that a bug?
Make sure your returning from the actual command callback rather than from inside a callback inside the command callback
oh
thanks!
Is it possible to use scripting to make my block interact with projectiles? For example, vanilla doors that open when hit by a wind charge.
Yes, you would need a ticking component to just test for the projectile around it
Could you not subscribe to the projectile hitting a block?
is it possible to get rarity items in itemStack?
I forgot that was a thing, I'm not home
Is it normal for Mojang to constantly break parts if addons when they force push those updates onto everyone?
only if you use experimental features
e.g ur addon uses one of the experiments toggle
So, for instance, are block IDs an "experimental feature"?
no?
experimental features are something you have to enable via world settings
ids arent safe either
for instance they recently changed chain to iron_chain
broke some of my stuff already on the marketplace
also VV broke stuff too. not to mention i some event order was also changed/ bugged, created a dupe for me for instance
I'm just complaining that they break stuff constantly between updates
Like that ID rename, very hard to deny
how can i change what silk touch drops?
because it seems to work mega dumb, always turning the block into item without consulting loot tables or anything
whats the point of adding a system if they themselves dont use it. i should just stop complaining really..
no way to check for silk touch enchantment either i see
you can get the silk touch on an item
import { ItemComponentTypes, Player, world } from '@minecraft/server';
world.afterEvents.itemUse.subscribe((eventData) => {
const { itemStack: item, source: player } = eventData;
if (!item || !(player instanceof Player)) return;
const enchants = item
.getComponent(ItemComponentTypes.Enchantable)
?.getEnchantments();
if (!enchants) return;
for (const enchant of enchants) {
if (enchant.type.id === 'silk_touch') {
player.onScreenDisplay.setActionBar('Silk Touch found!');
} else {
player.onScreenDisplay.setActionBar('No Silk Touch found.');
}
}
});```
how to get just the block that is in a specific world location? do I need to use BlockVolume?
dimension.getBlock
how? tried with const block = entity.dimension.getBlock(entity.location); but it didn't work
it didn't get the block that is in that location (the location of the entity, that's entity.location)
What did it do then?
idk but I'm running this and it's not placing the air block:javascript const block = entity.dimension.getBlock(entity.location); block.setPermutation(BlockPermutation.resolve('minecraft:air'));
and entity is valid
What block did it get?
I'm going to check
oh thank god! this will at least allow for workarounds
hmm... np, my fault 🙌
yeah so cancelling the break block before event doesnt cancel the drop whenn using silk touch leading to easy dupes and not being able to delete that pesky silk touch drop
are you sure you're using the event correctly? i just cancelled the block break and nothing ever drops unless the block is allowed to break
Yeah because the block doesn't break
what exactly are you trying to achieve?
cancel the silk touch drop
like i said above
since it blatantly ignores the loot tables
but you still want the block to break?
export function managePlayer(player: Player, target: Data): void {
const form = new ModalFormData()
.title(prefix)
.textField("Name", "Nom du joueur", target.name)
.textField("Id", "Identifiant unique", target.id)
.textField("Init ?", "Initialisé ?", target.isInit.toString())
.textField("In Nation ?", "Fait partie d'une nation ?", target.isInNation.toString())
.textField("Leave ?", "A quitté ?", target.isLeave.toString())
.textField("Gold", "Or", target.gold.toString())
.textField("Gemmes", "Gemmes", target.gemmes.toString())
.textField("Zone", "Zone actuelle", target.zone)
.textField("XP Sound", "Son XP activé ?", target.param.xpSound.toString())
.textField("Can Build ?", "Peut construire ?", target.permission.canBuild.toString())
.textField("Can Kick ?", "Peut exclure ?", target.permission.canKick.toString())
.textField("Can Ban ?", "Peut bannir ?", target.permission.canBan.toString())
.textField("Deco Combat", "Admin DecoCombat ?", target.admin.decocombat.toString())
.textField("Time", "Temps", target.time.toString())
.textField("Vote Box", "Vote", target.box.vote.toString())
.textField("Boutique Box", "Boutique", target.box.boutique.toString())
.textField("Donjon Box", "Donjon", target.box.donjon.toString())
.textField("Boosts", "Boosts JSON", JSON.stringify(target.boost))
.textField("Mineur", "Niveau XP JSON", JSON.stringify(target.jobs.mineur))
.textField("Farmeur", "Niveau XP JSON", JSON.stringify(target.jobs.farmeur))
.textField("Hunter", "Niveau XP JSON", JSON.stringify(target.jobs.hunter));
// @ts-ignore
form.show(player).then(r => {
if (r.canceled) return;
});
}
Hi, someone knows why it doesn’t work
.textField('label', 'placeholderText', {
defaultValue?: 'defaultValue',
tooltip?: 'tooltip'
})```
If you're using the latest modules this is textField
thank you
Yes
I have a workaround that works but it's ass really.
wouldn't you just disable the enchant at that point?
unless you're doing this to use silk touch for it's own loot pool
My block has an item that just drops in some circumstances & when it drops it has extra components
I drop it with an event. The silk touch logic straight up drops the block as item no question asked, doesn't go throug the loot tables like it should like it does in java, like it should
And the break before event is bugged. I'm just complaining here I guess, I have a mega hack that kills the item as it spawns
Also it's crazy that you can't have blocks that don't also have a block item
is it possible to get the shulker boxes inventory when its in an item form?
Odd request but woudl it be possible to detect if and X and a separate Z coordinate intersect and place a block where they do.
Ig 0 0 10 and 10 0 0 would place a block at 10 0 10
(The range can be limited ofc)
Sounds like you want to take the larger (or smaller) of the x- and z-axes.
hi, is it possible to modify the drop rate of an item example the saplings of tree ?
and is it possible to change the spawn rate of the mob?
Hi does anyone know how to import scripts into the main.js file
Like other scripts in the scripts folder and reference in the main.js file
here is an example import { Data, setMainData } from "src/lib/database"
Can you only import functions or can you import the whole file?
To be fair, Minecraft: Java Edition was created many years before the Bedrock engine existed. Bedrock is a separate engine built in C++ with its own design goals, such as improved performance and cross-platform support. Re-creating the full range of Java Edition’s behavior on a completely different engine is extremely complex, so differences are inevitable. Still, Mojang has steadily worked over the years to bring more parity between the two editions, and many Java like features have gradually made their way into Bedrock.
posibble

Does using beforeOnPlayerPlace custom block component not work properly? I'm trying to use it to replace the permutation of the block when it gets placed. I have a post up if anyone could help
so how?
idk
