#Script API General
1 messages · Page 126 of 1
there's resolve.
Oh right
i dont think you can directly modify the potion's level but you can replace it with a new one with this.
Okay, what about tipped arrows..? do those use the potion component?
I dont think we can yet
you can use the replaceItem command instead
Thank you!
im getting potion component undefined..? im remaking the loot vaults to be reusable so its in the onPlayerInteract hook of the blocks custom component registry.
you dont get the potion component for this, you import Potions and use the resolve method.
does the ominous_bottle even use the potion effect system..?
try and see, Im just assuming so.
it doesnt...
Can i not use the LootItem function? Im relatively new to scripting so idk how to do some suff
^^^ meant to reply to you.
oh yeah you can
good idea
create a loot table, then use loot table manager to get the itemstack from it
I am using the vanilla trial vault loot tables and they are using a loot table manager but dispensing enchantless items.
const ltm = world.getLootTableManager()
const bottleLoot = ltm.getLootTable('your_loot') // if having it in subfolder just do "subfolder/your_loot"
const bottle = ltm.generateLootFromTable(bottleLoot)[0] // assuming it would just be 1 item, just get the first index
inv.setItem(slot, bottle)
just create your own
and use the loot table set_ominous_bottle function inside the loot table file to set the level
I’ll try this, using generate loot from table generates an array of item stacks, I’m trying to either modify those item stacks before I “dispense” them, or modify the item entity right after it is dispensed.
The vanilla loot table has these functions already though.. so am I using the generatelootfromtable wrong? I’m just calling it on the vanilla table, then using a for loop to summonItem(itemstack.typeId, itemstack.amount)
I would just personally make my own loot table
Ok, I’ll try that when I get home from work, thanks.
Do you think I’m losing some of the data of the itemStack[] in the way I’m using it maybe? I can send you a snippet of my code if that helps. (Thanks for your helpXD)
sure, share it
Ok, hold up.. I think I might have figured it out… I’ll try it when I get home in a few hrs and update youXD thanks again for your help
I’m iterating through the itemstack array, and creating a NEW itemstack with that itemstack iterations typeid and amount, and then dispensing THAT. I should just be dispensing the original iteration itemstack.. right..?
yeah you are just making the code more complicated
the itemstack is already provided
plus the new itemstack you are creating wont magically get its data
i see why its not working now
So that’s gotta be the problemXD I FEEL SO STUPID!! Hahaha, ok well.. tysm for the help.
sometimes you gotta talk it through to figure out shit, no problem
well well well
How do I place block in specific coords, tried getBlock to setType but errors if undefined
idk
Tf you mean idk
const dimension = world.getDimension("overworld");
const placeLocation = { x: 0, y: 0, z: 0 };
if (dimension.isChunkLoaded(placeLocation) {
dimension.getBlock(placeLocation).setType("stone");
}
should be easy enough
What error exactly? Ensure if the world is loaded, And if the chunk is loaded, where you are getting the block.
There's also setBlockType() too.
Did something like that but on entity.dimension, sometimes the getBlock returns undefined if block in that position didn't exist
Didn't notice that, thanks
Oh. Check if the location is valid. Is that a void block? Unless your luck would be checking if the chunk is loaded, if you are trying to access a block far from player.
maybe I can't use getBlock if its air
Ye it's void
You can.
oh. then how do you expect to place blocks there-
Oh alright, thanks again
this was the fix btw, XD cant believe I spent 6 hours trying to fix that.. it was 5 lines of code...
can we get the type id of the entity inside the monster spawner block?
No not currently
It uses meta data which we can’t access you with scripting
Alright, I need some clarification: I'm trying to optimize my script so the game can run better. When would be a good time to use runJob?
Whenever you're doing a large amount of things at once that don't have to be done in a single tick such as filling in a large area
I have a script that resolves every block permutation in the game at once which causes the world to freeze for a few seconds as it's not going onto the next tick until the script is finished, if I used runJob I would be able to split the permutations being resolved between multiple ticks
Alright then, where would I use the yield keyword? I have seen it in other script files using runJob, but I don't know where the right place to put it is.
for runJob you yield every time you want to give minecraft the opportunity to move to the next tick
system.runJob(myJob);
function* myJob() {
doSomethingThatMightTakeAges();
yield; // If the previous thing took a long time, the game will move to the next tick here. If there is still time left in the tick, the job will continue running in the same tick
doSomethingElseThatMightTakeAges();
yield;
console.log("job finished");
}
most of the optimisation in scripting comes from reducing the number of API calls so that things take less time rather than using jobs to split something that takes a long time into smaller portions
Thank you! That honestly makes sense. I assume reducing the number of system.runIntervals that are lengthy should help right?
yes, with intervals I often see people getting all players in the world every tick which is unnecessarily slowing things down
in that case you should have a players variable outside of the interval and update it whenever a player joins or leaves the world
That can work? I'm still learning about what you can do in Javascript, but I wasn't sure if values outside of functions, system calls, and API events would even save data.
If you have variables in the root of the file the value will last until you leave or reload the world
That's really great to know! But doesn't that also mean that having too many variables with large data will lag the game then?
If it's a case where you need the players every tick then you'll have the same amount of data except the game won't have to create a new array of Player instances every tick
but if the interval stops at some point and the array of players is no longer needed, it would definitely be a good idea to remove the value e.g. set it to undefined
That makes sense. Thank you!
Anyone got any theories as to why my projectile has an undefined owner??
const projs = world.getDimension(dimension).getEntities({ location: loc, maxDistance: 64, families: ["projectile"] })
if (!projs) return;
projs.forEach(proj => {
if (proj.typeId == "pro") {
const owner = (proj.getComponent("projectile")).owner
console.error(owner)```
Projectile is a custom one that doesn't have a runtime identifier in it, but I dont' think that would affect it.
If you've spawned it with scripts too then it likely hasnt had its owner defined
Forgot to add that, sorry. It's spawned through behavior.ranged_attack
Maybe there's a subvalue for keep owner? I'll check, I doubt it tho.
Yeah, nothing.
Are ranged attack behaviour entities usually unaffected by their weapons?
Hmmm I think it depends on the projectile. You can define that the player not be affected or is affected in the components iirc.
So by definition it should store the owner... I have no idea what I'm missing tho.
Seems that's experimental, and is more like a filter than what I remembered.
Ugh, maybe I'll just reluctantly tag the owner as it leaves the "barrel". I feel like I'm going to lose a tick somewhere for some reason with that method though.
i just had the same problem
i made a workaround tho
Same, super clunky though. Having timing issues with it. handed off my entity spawn tag with a timer inside to a runinterval 😭
What was your work around?
mine only works if its spawned with script api im prety sure
when i shoot projectile i set a owner dynamicproperty with the id of the owner
and then when i want to retrieve the owner it repeats through all entities in the world for that id
I think that would work with projectiles from ranged attacks too.
I basically did the same, but with tags... I forgot why I did tags tbh.
Do you have something you could test this on yours with? I'm curious if this is a Mojang issue.
Well i was also confused with the projectile owner
Yeah, it should be working fine.
Hey quick question if you or anyone knows. Do DynamicProperties that are stored related to an entity go away when the entity dies? It seems like they do, but I have like 90 dynprops going rn hard to tell.
yes they do
but u can check them before entity remove
Oh wait there's why I used tags, I didn't want one more action that had to grab the closest entity so I did it with commands.
which i use for kill detectioon
Ok awesome, thank you!
my addon isnt very optimised
but i think i should optimise it after it atually works...
I've gotten stuck so many times doing that, I usually forget what my code means after I'm finished with a section so for me I have to do it up front 😢
Does anyone know how to change the value of a variable in the player's file using playanimation or any other method that isn't a property via the script?
You can't carry values to animations through script, but my work around is to execute a command in the script to do that.
like this?
You can add variables in the command: "playanimation". It throws a code in my experience though. But you can hide that and it works:
I do this through playanimation and it works perfectly, but only for attachables, not for the player.
ops
Some variables can't be changed that way.
I'm not sure then, maybe a better question for: #1070606638525980753 or #1067869288859447416
have u tried entity properties?
turn the sync on so it also goes to the resource side
the property should be carry over and this can be changed using commands
event entity
I don't want to use Properts, it has a very low limit, I need at least 20
can u not js have very explicit properties
like if u made all the properties just numbers
theres a tons of combinations
What I'm doing is complicated to explain via chat, but I need individual values for each property, and there are more than 20 properties, so I have to do it this way.
have u tried messing around with variables in the rp entity ?
I managed to solve it, thank you for your help.
nice
How are you spawning projectile from the api? I went to the end of my method and it just isn't working, need to know who the owner is to carry variables through properties 😭 . 6 hrs wasted.
Holy sorry u replied at 6am
Dimension spawn entity
Then entity.getComponent('projectile').shoot(the settings here)
perhaps ```js
entity.getComponent("projectile").owner = player
for some reason thats weird
try it
i have..
and...
bugged it is then
i just tested, it works... in beta
import { world, system } from "@minecraft/server";
system.runInterval(() => {
const ovw = world.getDimension("overworld");
const player = world.getPlayers()[0];
if (!player) return;
const arrow = ovw.spawnEntity("minecraft:arrow", {
...player.location,
y: player.location.y + 5,
});
arrow.getComponent("projectile").owner = player;// may damage the player when not assigned
}, 40);
world.afterEvents.projectileHitBlock.subscribe((ev) => {
const proj = ev.projectile.getComponent("projectile");
world.sendMessage(proj.owner.name + ` owns the projectile`);
});
Im pretty sure it works in stable
it does
@clever smelt
on sum script api generak typeshi
First add this field at BP manifest:
"dependencies": [
{
"uuid": "7641223a-0846-4c3a-97e3-9fb0a295269d",
"version": [
1,
0,
219
]
},
{
"module_name": "@minecraft/server",
"version": "2.3.0"
},
{
"module_name": "@minecraft/server-ui",
"version": "2.0.0"
}
]
Like that:
{
"format_version": 2,
"metadata": {
"product_type": "addon",
"authors": [
"VictãoSigma"
],
"generated_with": {
"bridge": [
"2.7.52"
],
"dash": [
"0.11.7"
]
}
},
"header": {
"name": "Aurorian Progression",
"description": "A pack that improves the craftings of the items in a realistic way. Progression was also reimagined to involve real life steps that ressemble the evolution of the humanity. Think you can beat this challenge?",
"min_engine_version": [
1,
21,
120
],
"uuid": "c70b54ae-3208-4b49-9458-d881cfa0c69b",
"version": [
1,
0,
219
]
},
"modules": [
{
"type": "data",
"uuid": "72cacb77-4e55-4276-9d2e-09ab743f20ed",
"version": [
1,
0,
0
]
},
{
"type": "script",
"language": "javascript",
"uuid": "3aff7ca8-a207-45db-9625-63e7eb840569",
"version": [
2,
0,
0
],
"entry": "scripts/aca_main.js"
}
],
"dependencies": [
{
"uuid": "7641223a-0846-4c3a-97e3-9fb0a295269d",
"version": [
1,
0,
219
]
},
{
"module_name": "@minecraft/server",
"version": "2.3.0"
},
{
"module_name": "@minecraft/server-ui",
"version": "2.0.0"
}
]
}
Don’t directly copy this code, as it will change a lot of things on your addon
Just add that on yours
okeh after doin the manifest stuff whaddo i do next
Need one more thing on manifest. Add that at modules[]:
{
"type": "script",
"language": "javascript",
"uuid": "3aff7ca8-a207-45db-9625-63e7eb840569",
"version": [
2,
0,
0
],
"entry": "scripts/main.js"
}```
Yes, now you create a folder called “scripts”
yes yes, ive made it in bridge
After that you create a file called “main.js”
ye its there
And paste that on it:
import { world, server } from “@minecraft/server”;
system.runInterval(() => {
for ( const player of world.getAllPlayers() ) {
if ( player.isSneaking && !player.hasTag(“sneaking”) ) player.addTag(“sneaking”)
else if ( !player.isSneaking && player.hasTag(“sneaking”) ) player.removeTag(“sneaking”);
else continue;
}
}, 1);
If you selected a template, delete everything
That’s already complete
Also, it’s based on tags, so if player is sneaking, it adds the tag “sneaking”. If not, it removes the tag. So you won’t need further scripts
And can do the logic via commands
ok 💔
yippe
Just the content on file
so i can now run functions w that tag yes?
Not the files & folders
Yep
No problem
i shall remember this act of kindness
Appreciate
Hmm, owner isn’t automatically assigned upon spawning? Going to try this in a bit.
Ooh ok, thank you! 😆 np, that was 10pm my time, must be in very different places.
how can i fix the issue of main hand being empty?
im using script api to detect the main items lore
If its undefined, skip it.
Open a post with your code and content log then.
nvm getequipment slots never return undefined as even air isnt undefined
ive been using getequpmentslot instead of get equipment
Does lore return undefined or empty array?
empty array
i'll go with
import{EntityEquippableComponent as eec, EquipmentSlot as es}from"@minecraft/server"
let V1 = player.getComponent(eec.componentId).getEquipment(es.Mainhand)
if(V1)return
mb forgot to mention i solved the issue
🗣️ 🔥 🔥
actually i did
sorry not mking it clear
i don't like using
import * as mc
tbh
i use it so i dont need to import anything in the future
but its prob not the best idea
understandable, but if you create a big project, it could affect your file size
🗣️ 🔥 🔥
is apply knockback better than impulse
what's the purpose you wanted?
smooth movement better with impulsr
like how transition sine in and out
set it to verbose may be easier for diagnose
but somehow you'll see some vanilla mob has error due ro their attack inverval never declared
it's assiganble anytime, actually
how can i use before player place and before interact with block to place a block?
currently im canceling block interactions
but that cancels block places
i need to cancel block interactions but let them place still
Sorry, I mean, is it automatically assigned upon firing?
(From a behavior ranged attack)
who's firing, player or entity?
i havent tested the projectile owned by a non-player tho
entity
"minecraft:cooldown": {
"category": "cosmos:asteroid_annihilator",
"duration": 0.5
}```
how do i like activate the cooldown using scripts
player.startItemCooldown
Oh so that's how it's used, so that's why It didn't work on interaction (without js)
Lol
Its so helpful too, since you can give the item cooldown any length of time you want, independent of how long it would be with the item json
No problem
Gotta use that now
Much useful than making manual cooldown that's buggy
Honestly, too true
And paired with itemStartUse and itemStopUse you can then set a cooldown after you release the interact button and even make the cooldown a dynamic length of time based off how long you held on the item
and the category can be ANYTHING
Even if it doesn't exist on any item...
no way, that's cool, I thought its based off only on json
Very nice, I thought it needed it, coz the api has argument to put a category id
I don't have a clue on what that could be used for though
Any ideas?
just a simple timer
where is minecraft path located at windows?
its been a while i use windows for coding addons
so i forgot
i remember it used to be on app data
Legends lang nakakaalam
?
Try localappdata%\Packages\Microsoft.MinecraftUWP_8wekyb3d8bbwe\LocalState\games\com.mojang
thank you, imma try it
hell yeah
i think i found it
thanks for the help my guy
what's the difference between
function Test(){}
and
function* Test2(){}
Test2 is returns a generator
What
you can use it to yield values
Oh
and then use them in a loop
i mean do it makes difference for low-end performance?
function* EvenNumbers(){
let i = 0;
while(true) if(i % 2) yield i;
}
for(const n of EvenNumbers()) console.log(n); //1,3,5,7,9,11, etc
its slightly slower compared to raw loops
@wild hazel your enemy @broken pawn ||(sorry for ping)||
even though more flexible
because its a state machine
internally this kind of thing is implemented with an state machine
understandable
so it executes a function, returns the actual state, you use it
then i'll stick with the first one
🗣️ 🔥 🔥 🔥
internally isnt much different than simply
const obj = { generate(){return {completed: false, value: 5}}}
while(!obj.generate().completed) {
dothing();
}
but with more logic inside the obj
👍 🗣️ 🔥
it could be better for performance if you're dealing with collections
such as array
this generator can have methods https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator
if it was already implemented on quickjs for sure
all i can say is:
there's 12 function running at runInterval (10 Tick)
and all of them uses "for(Let A of world.getAllPlayers())"
but there are methods like filter, every, take, map, etc, theyre(i expect) lazy
so you can do something like
const generator = generator_func().map(f1).map(f2).filter(f3).map(f4).take(12);
and when looping it will execute a single loop
internally arrays can do the same but for each map, filter, and etc, its a loop by itself
with tends to be O(M*N)
function* Test2() {
yield 1;
yield 2;
yield 3;
}
const gen = Test2();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }
with these generators its just O(N)
sounds like compressing everything into a single pack
its, it probably just stores a function to map and filter things
and when iterating use it
M = amount of functions that mutate the array, or the collection,
N = amount of data on the collection
pretty useful by the way
It's like a lazy function
imma about to take a nap sorry, here's 00.24
anyway, thank you for the explanation 🗣️ 🔥 🔥
Before async/await, they use this I think
as far as i know, they did
async functions are state machines as well
so its comprehensible it to be implemented like it internally
Yes you're right
Good point
How do I see dps in a world? suggest me a software.
NBT Editor
Link
What's the problem in this:
player.onScreenDisplay.setTitle("§lUNVANISHED", {subtitle: msg}) //msg is already defined here
The log:
[Scripting][error]-TypeError: Native setter cannot be assigned null or undefined. Interface property ['stayDuration'] expected type: number (failed parsing interface to Function argument [1]). at unvanish (main.js:39)
at VanishFunc (main.js:60)
at <anonymous> (vanishitem.js:9)
Can having multiple of the same event cause any performance issues
https://stirante.com/script/server/2.4.0/interfaces/TitleDisplayOptions.html
It requires the mandatory properties.
Documentation for @minecraft/server
Not from what I can tell.
Ohh, thank you
Is there an event about tick changes
Tick changes?
Like an event that activates repeatedly
Because system.runInterval crashes on mine when it's running too long
Or if there are workarounds
Never had this issue. What are you executing?
Sometimes when I reopen my Minecraft app, it gives me crash leave about can't handle watchdog
Oh wait I think its because of my creator setting's watchdog
How do I force a player's rotation?
teleportation
setRotation wont work
do i HAVE to have a discord bot to link mc account to discord
What do you mean by linking?
Applications connections, your own system that pairs account?
It really depends on what you need
like account pairing i guess
just link discord account to mc xuid
i was thinking
For my server network, I am using an external backend to pair both services
Are you using NoSQL or SQL database?
well idk
im currently using supabase
will most likely switch to sql in the future
CREATE TABLE IF NOT EXISTS discord_connections (
userId VARCHAR(20) NOT NULL UNIQUE,
xuid VARCHAR(20) NOT NULL UNIQUE
)
And then just check if any entry (XUID/Discord's user ID) already exists in a database
ahh yeah
so wait
i would need to verify on discord though
i dont want people linking other players discord accounts
You also probably have to implement some code system, like you'll generate a code for 5-10 mins and user in Minecraft will have to type it in
Yup, I just wanted to mention that
This is the most popular method AFAIK, even The Hive uses this
generates a code for their xuid in supabase
but then i do need a bot
to detect stuff in discord
This bot does not have to implement a lot of things, just simple connections via HTTP requests
Install discord.js to simplify your process and it shouldn't take longer than 30-60 minutes tbh
i just dont wanna host it on the same vps
so i might just buy anothe rone
unless u can host them for free somewhere
Use Docker containers to make deployment easier
I host sometimes 2-3 containers on a single VPS and it runs smoothly
Railway is pretty nice
I use OVHcloud most of the time, I don't really care about noisy neighbour problem tbh
yupppppp im using ovhcloud
its crazy how cheap it is
They have a profit because of enterprise plans
are u using vps 2026?
Regular customers are very few percent of their yearly revenue
vps-2 can handle 25 players with 19-20 tps dips
on a factions
7000 chunks loaded
and its freaking $7 a month
a realm would explode
they would go offline again if i tried that
That's not that well optimized, I could get 50-60 players and server was running smoothly
Are you sure that you've configured your server correctly?
well its not mine tbf
Oh, lol
but they havent tested more than 25 so
but damn thats crazy
i have noticed though
around 300-350 entities starts to dip the tps
Entities are the worst thing to server's TPS
yeah 😭
You can get up to 50-60 players easily if you simply cut entities down as much as you can
Even on VPS-1 it would be possible tbh
If you also configure your server correctly to prevent from loading plenty of chunks, change compression method etc.
Use "snappy"
And only compress larger than 512/1024 bytes
Yes, in server.properties there are dedicated options to choose how a software will compress all packets
Yup
it was on zlib and 1 💀
If you're using zlib, it's better to use ~10k
10240 is a good value
💀
The only con of Snappy is that few percent of players will be unable to join your server, but I don't really know anyone that couldn't join my server because of that, so you shouldn't worry about it anyways
its the easiest thing to set up but i cant get it to work with debian
Do you use PM2 for BDS or what?
I prefer to wrap everything around Docker Containers, it makes my workflow much easier tbh
Docker is the biggest game-changer. It's high in demand, also makes any deployment much easier
You will never encounter error "It works on my machine" if you start using Docker
so what even is docker
Docker is a software that allows you to run softwares inside "containers", which are isolated microservices
block.permutation.getState('growth');
Thanks, I also figured it out
Is there any way to hide effect particles when using .addEffect in my script? I'm new to this so sorry if that sounds dumb.
Yes, pass in the options.
https://stirante.com/script/server/2.4.0/interfaces/EntityEffectOptions.html
Documentation for @minecraft/server
Thank you very much!
is it possible to dynamically change the generic speed of a pickaxe in script api without applying efficiency or haste
No
ok thx
No problem
how to make addons achievement friendly?
add this to your behavior manifest
"metadata": {
"product_type": "addon"
}
ty
when did this exist
since minecraft sells addons
2 years ago
yeah ive found out like almost a year ago I think
Is there any EntityHurtBeforeEvent alternative that works on normal versions of mc and not just preview ones or nah
Editing json. Thats it.
as long as the code inside nothing crazy
You could also make ones that run for a limited time and then cancel them depending on what your doing
Alr thanks yall
whats the lore limit per line
Pretty sure it's like 1k characters per line and 100 lines or some shit like that
anyone know a good way to get the nearest structure? im trying to determine (roughly) where the nearest ancient city is so that as chunks load I can determine if I want my code to run or not.
how to check if the block hasTag via script api on beforeEvents.playerBreakBlock ?
i mean, is it possible?
is it possible to make a scoreboard number go up to 9 quintillion
Quick question, did dynamicProperties change at all in how they are linked per uuid vs world?
UUID
You will have to split it across multiple different scoreboards
Ok
Well I thought it was uuid, up until I changed version and uuid for someone that has a realm, the pack updated good, but data was still there lol. So maybe a fluke
Make sure the realm took the update. Usually when that happens it is a sign that the realm is still using the previous version.
Okay!
Also, the data won't be deleted when you change the UUID. Just to be sure for clarity lol. It just won't be accessible.
Hmm weird lol
They confirmed the update took and data stayed idek, update changed some big ui things
Update the manifest to include some random description then try again and verify if the Realm is using the behavior pack with that modified description. Best way to confirm that it's using the updated pack. I typically add a version at the end of the description for this reason.
Okay, it could be a simple misunderstanding on my end. Thanks guys!
Can also add a basic command to print the version in chat. Another good way to verify lol.
Legendary idea lol
Hate realms
Indeed lol
They are a pain in the arse. I’m glad I got a PC and use BDS instead lol
I highly recommend going over to endstone. It is a wrapper, and still supports scripts, but also does python and c++ plugins.
Cool alright
Was there a shortcut to summon entity with pre inserted event
I remember to some source codes it was like entity<event> but I'm not sure
dimension.spawnEntity(id, location { spawnEvent: event });
does anyone know how to disable commands on endstone
You can use BDS to disable commands
config/commands.json
{
"permission_levels": {
"me": "owner"
}
}
it doesnt seem to work on endstone
{
"permission_levels": {
"me": "internal"
}
}```
supposedly i have to use plugins but i do not wanna do that
It only works for you, other people cannot use it
Did you restart your server?
yes
i finally got this down
now time to make /link
Is that bds
Also can I know your font rp, just the png file if possible
No other way with endstone sadly
No, he can disable a command by using permissions.
Even darknavi has mentioned it 🙂
im trying to use player.getComponent('inventory').container to see if player has the items it needs for a craft and if it does it removes it and adds the crafted item
anyone know how i could do that?
use a for loop.
https://www.w3schools.com/js/js_loop_for.asp
...
i think i need a loop but idk what functions detects items
nor how to remove a specific number
getItem()
on the container class.
const container = player.getComponent('inventory').container
for (let i = 0; i < container.size; i++) {
const item = container.getItem(i)
//...
}
nvm
nvm what
theres a contains function
that wont work well.
😭 about to tell me 50 negatives of it
that checks for an exact copy of the itemstack.
well for my purposes i inputed contains 10 oak planks and i had 15 in my inv it returned true
so i think for my purpose it will work
this wont work if i have the items in different stacks
well im prety sure
imagine i got 2 stacks 1 has 9 planks the other has 6 planks
thats why you put break at the end so it breaks the loop.
.
i didnt give a complete script, it was just a snippet.
@thorn flicker how would i remove items if its in a seperate slot
so it would remove 6 from the first slot the the rest of the 4 from the other
this is a problem, you are right, but im busy rn
sorry
all good
👍🏻 manage to figure it out by making a for loop for how many i want to remove and 1 by 1 removing it from each stack
I recommend reading my messages for the future
anyone got entity cloner
You're wrong. You can disable commands without using a plugin.
Literally Mojang employee even said how to do it
As external tool?
Or script api immitation?
bc you are not possible to do it only with script as all components are not accesible or modificable
noo they arent wrong, currently there is a bug with endstone that doesnt let u disable vanilla commands like that
supposedly itll be fixed next update
yes its possible with vanilla bds but i run endstone so it doesnt work
I've used this method few months ago and it worked correctly; to be honest, it's still better to wait for my approach rather than using plugins
They're not that reliable in my opinion
yeah i really dont wanna touch plugins but look
If you don't use plugins, it's better to use regular BDS at this point
Larger server networks use BDS with a proxy rather than a mod-loader like Endstone
config/commands.json
well i need access to xuid
I am reading BDS's console and scrap it out from there
yeah i have a friend who does that
but i also need boss bar and stuff for my json ui
its smart but ehh
i like the better control
ip bans
in the future i may use plugins purely for alt detection and vpn stuff
I've stopped using Endstone when I started using a proxy, it's easier to maintain and I am not depending on someone that might just stop working on a software anyways
well i heard that they are backed by someone and are paid loadsss to keep it updated
tbf it does update every release
but not with loads of features just the newest version
Endstone is only good for server that do not bypass more than 30-40 players online tbh
Is there an event to detect if a block is being generated, such as cobblestone generator, cabalt generator and other causes
Damn
Thanks
how so??
well actually i get what you mean kinda
If you have more than 40 players, you'll start thinking about moving to your own infra etc.; most of bigger networks do not want to rely on OSS projects that they can't even maintain. Look at The Hive - they have their own software, Zeqa is using PMMP but owner of a server also maintains PMMP
yeah
PokeBedrock also uses BDS with a proxy that is maintained by the owner
but isnt pmmp php?
i guess like
building your own endstone like software would be cool
In my opinion, it's better to use a proxy rather than a mod-loader if you'd like to code one
1
8 digits and it can be negative, so 8 chars
perfect
const isLengthValid = (auxId) => {
const numerical = Number(auxId)
if (Number.isNaN(numerical) || !Number.isInteger(numerical)) return false
return auxId.length <= (7 + Number(auxId < 0))
}
its 3:56
Yes
now its 3:57
It's 9:57
No
Yes
My goal is to develop an entity replay system.
Anyone happen to know why these don't work anymore? MC Chat says it is applied or asked, but it does not work. There are no errors, either.
{
system.afterEvents.scriptEventReceive.subscribe((event) => {
const { id, sourceEntity } = event;
if (id === "og:retshort" && sourceEntity) {
const direction = sourceEntity.getViewDirection();
const horizontalStrength = -3.0;
const verticalStrength = 0.5;
sourceEntity.applyKnockback(
direction.x,
direction.z,
horizontalStrength,
verticalStrength
);
}
});
}
my eyes
Can you send what command have you used?
Also, applyKnockback is a bit different
Do not use examples, beacuse they're outdated sometimes (and this example is a pure evidence)
npm install brain
/scriptevent mw:retshort
my math is correct for aux ids correct??
const itemId = typeIdToID.get("minecraft:stick");
const enchanted = false;
const encoded = (itemId ?? 0) * 65536 + (enchanted ? 32768 : 0);
it only seems to work for blocks
It should be correct
it doesnt display items properly
Maybe there's custom items?
nope
i have 0 custom items
22773760 is the aux id for diamond_sword
displays nothing
Maybe you have an outdated hashmap
i doubt it because all the other stuff works
and it would just shift the ids
blocks work and shields work
like stone works
Hmm, I haven't encountered an issue like this before yet
paper doesnt work
Is paper in your hashmap?
If you manually put the aux it still doesn't show up?
like directly put it
i know there's no difference but trying ain't bad
yeah i tried that 😭
what the heck is this ???
nvm that doesnt matter
yeah its still all broken
im directly displaying the aux id and it only works for blocks
emerald: 36175872
enchanting_table: 7602176
emerald doesnt work but enchanting table does
what did minecraft do
is structure cloning out of the options?
There's this weird thing happening when you get the block container of a single chest that was just spawned via structure load (the chest has loot table in it) , then get the emptySlots it returns 27, even though, when you open it, there's loot inside it or if you destroy the chest block.
Not sure if this is intensional, i know it could probably be an optimized way to only get items when breaking it or opening it, i was trying to get like the explorer_map using loot_tables via script or command, but keep getting empty container instead.
P.S When you break the chest block it drops the items, although the explorer map is still not functioning, the only way to make it function properly is when you open the chest, which sucks.
Do I can directly transport the same item to another player like
anotherPlayer.getComponent("minecraft:inventory").container. addItem(data.itemStack) //or data.itemStack.clone()
yes
btw,
where's data coming from?
u could directly tranfer via, .container.transferItem instead of addItem
if possible
Oh yeah I forgot
But it's buggy
It's delayed response
alr then
might need this```js
const c = anotherPlayer.getComponent("inventory").container;
const remaining = c.addItem(data.itemStack);
if (remaining) {
anotherPlayer.dimension.spawnItem(remaining, anotherPlayer.location);
}
I already know what to do, but why you gotta spawn an item also
when the inv is full
np
I forgot itemstack returns that when it fails to fill up the container
Pinoy din pala amp
At first I thought it returns falsy when it fails
can't remember other's code much, unfortunately
is there any afterEvent that gets triggered when the player is fully loaded? basically when you can actually start playing
Player spawn?
that one seems to be triggered before you can play
im trying to get the simulation distance
function getSimDist(player) {
const pos = player.location;
for (let i = 16; i <= 196; i += 16) {
const loc = { x: pos.x + i, y: pos.y, z: pos.z };
try {
const block = player.dimension.getBlock(loc);
console.warn(block.x, block.y, block.z);
} catch {
return i - 16;
}
}
return 196;
}
this returns 0 with playerSpawn or playerJoin or even worldLoad
The closest thing to this behavior is PlayerSpawnAfterEvent, if you need to get simulation distance, just run your function until it's not 0
ooh the loop sounds good that'll work
I would actually just recommend using the dimension.isChunkLoaded function.
I didn’t know he used Endstone 0.10 at that time. I think Endstone users know better what works on Endstone and what doesn’t 🤷♂️
hmmm this might be the best solution indeed
I used structure blocks in mine
I also tried saving variant and available stuff but some things are not possible
Could you explain how you did it?
With structures?
Ye
Just used structure manager and saved a structure at the entity location, excluding blocks
There might be more than one entity in that location, so i did some other stuff to make sure i don't duplicate them
Like?
Can't really remember every detail, sense that was in a lost version (i only shared videos)
What i do remember is keeping track of the entity id when saving it, so i don't save it multiple times when looping through nearby entities.
You can also tp the entity before saving it to avoid that? Not sure if this will work tho
Wouldn’t be saving data and replaying it more reliable or even better?
as i said i tried that, it wasn't saving everything
https://www.youtube.com/watch?v=Rz3RKzubHpo
horse variant for example only save part of it
الفيديو عبارة عن استعراض لتقدمي فتطوير الربلاي مود لماينكرافت الجوال
Whoa, that's really awesome.l
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]
Scoreboards are better for keeping scores, system runs are better for running systems
Yea im guessing, but i did notice some people yk like, making spells and attacks with scoreboards, and others including me, use system runs
which one is better for that case?
Like for cooldowns between attacks and whatnot?
Yea
I’d say out of the two, scoreboards would be better, but I would say to use date timestamps or dynamic properties if you are using scripts
Date method lets you set the cooldown based on current time and not have to decrement or increment any values
Dynamic properties are built for scripts, and a lot easier to use
Date method isnt always reliable, if someone stops the game or the game is lagging it causes cooldowns to be faster couse they re not game dependent
just use the cooldown component?
I’d say that makes it more reliable than other methods
...
depend on the use case
should be considered if it can be used
yeah, if it is item related
it seems to be bit operations
rather than normal arithmetic ones
it might be something like
(itemId << 16) | (enchanted * (1 << 15))
which does almost the same
but the sum generaly isnt literally a sum
well tbf its not happening for me
i forgot the source of this but, sums are OR operations and multiplications are AND operations
i think i learned from boolean algebra
How did you do the riding thing?
When saving the ride, i save an object with timeframes and riders
oh my bad, missed that message entirely on my phone
is there a component for modifying how high a player can jump
- It's better to ask in #1067869022273667152
- There's no component like this, sadly 🙁
Ok nws
does anyone know why its not letting me import beforeEvents from server-admin?
its just not showing up, only variables, secrets and whatever else
In typings?
Is it possible to get like the maindhand or offhand or armor of any mobs (not player) using script, like return the itemStack?
No.
Ah okay
Is there any known workaround for these vanilla mobs to differentiate which ones are tamed to specific players?
That's just a link to one of the component's properties?
Did you check what is this property even for?
Yes, but it doesn't help for quite a few vanilla mobs because the tameable component gets removed as soon as they are tamed. This will just return undefined.
It's not this component. Read carefully
But tame mount will only work for the specific entities which have this component. I'm looking for a solution for all the tameable vanilla mobs.
There's no closer solution to your problem than mine. You can always copy vanilla mobs into your add-on and add this component
How do I stop the player from breaking a specific block
I want it to block the player from breaking it when they don't have permission
Like if they don't have the specific tag
playerBreakBlock beforeEvent
Documentation for @minecraft/server
set the cancel property to true
Thank you♥️
np
Bro shes not thanking you 😭
how can i runCommand on a player thats in the player selector for a custom command
they just dont work
im trying to foundPlayer.runCommand("kick @s")
NO I AM SAING "no problem"
as it was resolved
so there is no problem anymore
the longest awaited feature fr
why doesnt it exist 💀
who knows
what is up with this ```ts
commands.register({
name: "online-ban",
description: "Ban an online player from the server. Eg: /online-ban G07HN 'Cheating' '7d'",
parameters: [
{
mandatory: true,
name: "username",
type: CustomCommandParamType.PlayerSelector,
},
{
mandatory: true,
name: "reason",
type: CustomCommandParamType.String,
},
{
mandatory: true,
name: "duration",
type: CustomCommandParamType.String
},
],
permissionLevel: CommandPermissionLevel.GameDirectors,
callback: async (origin, player: any, reason: string, duration: string) => {
//const self = world.getPlayers().find(p => p.name === origin.sourceEntity?.nameTag)
const foundPlayer = player[0] as Player;
//if (foundPlayer.hasTag("owner")) return false
//if (foundPlayer.name === self.name) return false
if (!foundPlayer) {
return false;
}
if (duration.toLowerCase() === "forever") {
await bans.upsert({
xuid: foundPlayer.xuid,
username: foundPlayer.name,
reason: reason,
duration: formatDuration("1000w")
})
return true;
}
const durationSeconds = formatDuration(duration);
if (durationSeconds === null) {
return false;
}
await bans.upsert({
xuid: foundPlayer.xuid,
username: foundPlayer.name,
reason: reason,
duration: formatDuration(duration)
})
const reasonArray = [
"§cYou are banned from this server!",
`§r§7Reason: §b${reason}`,
`§r§7Duration: §b${reverseFormatDuration(Number(durationSeconds)) ?? "§bForever"}`
]
foundPlayer.runCommand(`kick @s "${reasonArray.join(" ")}"`);
return true;
}
});``` its not letting my run commands on the player
its adding to the database and stuff
Run as a dimension maybe
nope
foundPlayer.dimension.runCommand(`kick "${foundPlayer.name}" … `)
ya ik it doesnt work
i might know a way to crash them actually 💀
oh wait
okay so
its not finding the player properly???
bruh what idk
i cant run anything on the found player
not sendMessage
nothing
but i can get the name and everything else..??
foundPlayer is undefined then
but how if i can get the name??
Can't you use player's name directly instrad of a nametag?
and the tags it has
Use a string instead of PlayerSelector in username param
i just cant run stuff on them
tried that too
i get command failed
it wont run any commands on the player 💀
wtffff
first one fails, second one works..????
const foundPlayer = world.getPlayers({ name: player })[0];
console.warn(foundPlayer.name)
const worldPlayer = world.getPlayers({ name: foundPlayer.name })[0];
console.warn(JSON.stringify(worldPlayer.getTags()))
worldPlayer.sendMessage("test")```
might have found why
Idk if the player on {name: player} is a variable or not, but name should be name: "The Name"
Is there a way to detect when an entity has been dyed?
interaction?
But is there a way to do it in a script?
or just detect component group changes
I saw something like
DyeColor,But I don't know how to use it

that is probably for sign colors or items
use DataDrivenEntityTriggerAfterEvent
also, this is a wired name tbh
😔
keep in mind the evoker can chnage there color, so DataDrivenEntityTriggerAfterEvent might work best
when they spawn
e.setDynamicProperty('color', e.getComponent('color').value)
what does world.getPlayers return? does it give you a list of the players online or like a number
Actually it was EntityHurt before event and we already having it so
yea thats why its longest awaiting feature
you cant do @s, only name, just do kick ${foundPlayer.name}
nu uh u can
they added it back
when
no idea but it works
kick: {
value(reason: string) {
system.run(() => {
this.runCommand(`kick @s "${reason}"`);
})
}
}```
well, im trying to make a massive shockwave that happens after an event, it will release something like a circle that expands and knock back entities as it goes through them, so whats the most efficient way to do it?
visually? or what
getentities has max distance and min distance
so i assume just loop it the min and max distance going up by 1
well, i really hate using getEntities, its really really bad for TPS, so ill just use projectiles instead,
i can use this for the visual effects, its good enough ig
that looks good
what i will do:
spawning like 20 projectiles that can go through multiple entities, it moves slowly and u can jump above it to avoid it
spawning 20 projectile entities once every a while is so much better than using getEntities multiple times
for now, ill add the other projectiles first, then ill deal with that shockwave one
i mean, i can make it alot simpler, like one large projectile that explodes into 4-9 other smaller ones that explodes upon impact, each one will have a small shockwave and it covers a large random area,
Just checking that I haven't overcomplicated things for no reason, there's no easier way to check that an entity was killed by a charged creeper is there?
how tf do you export a typedef, i have tried making a module, i have tried importing the file, i have tried making an unused export, i keep getting the typedef not found in module error.
how is your code?
by the way, is there a method to get the uuid of the addon?
or must it be hardcoded?
Dependencies version are with string, not array
The ",," format?
okay i changed the dependency format to string, but now it says "at least one of your resource or behavior packs failed to load"
Do not care about this, sometimes it just sends on the chat
As far as any feature from your BP/RP works, omit this message
Yes, e.g. "2.4.0"
its supposed to show "hello world" when i use /reload but it doesnt happen
Can you show me your current manifest?
Use dots as a version
"2.4.0"
Also, fix caps on 7th line of main.js:
world.beforeEvents.chatSend.subscribe((event) => {
-# Just copy this to 7th line
alright gonna try now
Should work fine, LMK if it still fails
well it didnt failed but nothing happened
so im not sure if maybe the main is the one that needs something changed?
world.beforeEvents.chatSend.subscribe((event) => {
system.run(() => {
world.sendMessage(`[LOG] Player sent message: ${event.message}`)
})
})
subcribe?
Can absorption hearts be detected?
I fixed it, try now
You can only get the level of an effect, it's kinda hard to detect amount of absorption hearts that player has
THANKS
jesus js is so weird sometimes
tho it says something about cannot read property subscribe of undefined, thats normal?
That means the thing you're getting the subscribe property from doesn't exist
chatSend only exists in beta versions of @minecraft/server
oh, so should i remove/change it?
Adjust library's version to "2.5.0-beta"
not really
do you know where i can find these java scripts? so i know which ones are available in stable verions
thanks
Does anyone know how to get gametime?
Is that not just current tick?
no
?
i thought he meant the in game time
is it possible to make my entity follow a certain path till it finds a player? im trying to make a horror game and my entity j moves wherever he wants and the maps too big for that.
i was thinking where it follows certain blocks in the floor or something? then one player isnt a target it goes back to following them
Is it possible to use ItemStack to give potions?
how do you get equipment proprieties from zombies or non-player mobs?
const equipment = ent.getComponent("minecraft:equippable");
console.warn(ent.typeId); // returns minecraft:zombie
console.warn(equipment.totalArmor); // doesn't work
You can't
They disabled the component on non-player entities years ago and haven't ever mentioned adding support back

i saw theres a runCommand alternative with testfor but can it test for enchantments?
no

One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
You're using it incorrectly
It only takes entity.id
One message removed from a suspended account.
One message removed from a suspended account.
It only returns a single entity, and testing for families would return several
You might be mistakening this for world.getDimension("overworld").getEntities()
Doesn't need to be the overworld but just used it for the example
Nah, it's fine
We've all sucked at something before and this just looks like slight misrememberance
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
Strange
And it didn't work either
Maybe try this
console.warn(enemy.id)
The game might not be getting the enemy in the first place
This helps us make sure
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
I can't find where the docs include scoreboards
This one might not exist in the way you used it
Wait nvm, I cant read 😭
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
Oh, it does now?
What changed?
No problem ofc
One message removed from a suspended account.
These old days we had to use commands to set and get the scores 😭
back in my day...
Back in my day scoreboards never even existed (no one told me about them 😔)
These old days when we had to use Commands.run status message to test for stuff
Real do you guys remember Commands.run?
ye
I didn't remember how it was written tho
is appwrite or supabase better?? supabase is cleaner to use but appwrite has 4x more free storage 
the better option would be to host your own sql database on a vps but idk how to do all that
Appwrite: free, 2gb, sql style
Supabase: free, 500mb, sql style
Self-hoster: $4.90, 75gb, sql
how to import this module?
Completly wrong server, this server is for Bedrock add-ons
Also, to import a package in Java, you just have to import a class/interface etc.:
import net.minecraft.client.model.animal.chicken.ChickenModel;
Use Docker to host it easily
any tutorials?
Check out Docker before I put you in a container.
Download Docker Desktop: https://dockr.ly/3EbT6ol
The Docker Suite of Products: https://dockr.ly/40ybLSG
// DOCKER RESOURCES IF YOU'RE A NERD //
https://youtu.be/t779DVjCKCs?si=Tu10v76pS-t4fpfi
https://youtu.be/rIrNIzy6U_g?si=_UuH-jSFwRxcptjr
https://www.docker.com/resources/what-container/
http...
we got too much Java on JavaScript based channel lol
should i do my own CUSTOM sql db? or just build supabase and stuff
What do you mean by a custom? MySQL, PostgreSQL etc.?
yeah i guess
i really like the layout of supabase since i can have json b columns and stuff
PostgreSQL has the same features and you can easily self-host it on your own or even use like Supabase (serverless, e.g. via AWS services)
so for self hosting do i just read and write data through vps hosted local hosts??
since i can only do http requests with script api
Yep, you just send a request to your database
There are 2 ways:
- You make a backend and prepare routes like e.g. /guilds/all and you just fetch it.
- Single REST API endpoint and you just send there your SQL query
can i FULLY customize it?
like identify certain columns as indexes to performantly sort them
What are the dynamic properties limits?
can i save a 672 byte number on them?
You should stringify it before saving, but there's not much a limit of an amount of dynamic properties
There's only a char limit(or was it a size limit) per DP. 😓 I've reached that limit so many times.
my goal is to use the minimum amount of memory not to save it normally
i ve alredy reached an RGBH format in strings but i wanted to go further since a char heavier than a number
Oh, okay
Do you need to save this single number with a very high precision?
If not so, I'd save it in a scientific notation
i got it
omg
website where i can view all entries
What engine are you using?
5liter
these rookies man
fire
yes it needs to have 0% data loss its for a minimap
This is what i reached with 4 characters per block 3015 chunks in 3.47MB
Hey, weird question, ik they disabled the run command option we were used to and replaced it with onuse custom, anyone has a good guiode how to make a tool that when right clicked executes a function?
What im trying to do is
- create object
-create function
-object executes function when right clicked
-cooldown
But all guides are outdated and i cant find any good guide that explains correctly
.....
cool but only for mobile players
Who diceded that
I mean it work 100% both PC and mobile because you just need click the button
I don't know about console though
I didn't test it on console because I have only have phone and keyboard/w mouse that I buy online
All backpack add-ons should have this feature and this not finish yet
Ohhh wait I thought it was just the fake button method for mobile players
But it’s just an inventory slot
That you put items into
Very cool
Is there a way to detect the player holding the interact button on items that are not chargeable?
how can i spawn a baby black cat with scripting..? i know there is a "isBabyComponent" but idk how i can set it, and how i can spawn a specific variant.
nvm, got it.
General question, but does anybody do before and after metrics when refining their scripts?? If so, how?
anyone know which exact version was custom commands added?
are classes good to use for multiblocks?
Minecraft-Beta-Preview-1-21-80-22
i mean when it was added to main version
oh thanks
the minimum version is 1.21.100 with beta api 2.1.0
well, depend on how you intend to use them
Why does player.startItemCooldown doesn't work
Not that it didn't work, I just don't know how to make it work
Even if my custom item has minecraft:cooldown component, I can't start the item cooldown
show code
player.startItemCooldown("cd:leap", 20)
Because my item has component like:
"minecraft:cooldown": {
"category": "cd:leap",
"duration": 20
}
idk then 🤷♂️
@round bone so sick
their player data is bound to the island data
so an ID has to exist in players to exist in islands
You use self-hosted version?
yes
postgreSQL
i have to set up more security though
i want to host it on an actual website maybe
or just be able to read AND write from a different ip
i already have anon roles and a JWT key set up so i can just use that
👏
is there any apis i can use to grab the usage and performance?
how long reading and writing takes
You send requests directly to an engine or you use a backend microservice?
backend
Does anybody know if there is a way to trigger a screen shot on a server from a script?? I want to make a photo booth for my SMP that uploads to a discord server
u can't
But you can send the block data to the server so that the server can render it and take a "screenshot"
It was primarily to capture player skins for their bio, apparently taking a screenshot means to some people take a photo of the screen with your phone!!
