#Script API General
1 messages · Page 127 of 1
It's very common, and also nice at the same time
😉
yeah its so easy to run multiple things at once
so i dont have to use pm2
but i will only use docker for the database and othe rmisc stuff
i think i should run a discord bot and the bds on pm2 just for easy production
does script api have access to process env?
Nope, it does not :/
The closest thing are server's secrets
yoo
i haven't scripted in a while
hope y'all are doing nice
so anyone know how many ticks i have to wait before a chunk is loaded by a ticking area command?
Any reason you're using commands and not the ticking area manager?
Documentation for @minecraft/server
thanks
Nice
so, im making my entity summons other entities close to it, and its showing alot of logs when the entity is not loaded or the spawning area is inside an unloaded chunk, so how am i going to detect if the spawning location is valid or not?
dimension.isChunkLoaded
if (dim?.isChunkLoaded({x:dX, y:dY, z:dZ})) dim?.spawnEntity('xhardercore:ender_bullet_rain', {x:dX, y:dY, z:dZ}); should do it ig,
what i should do is adding a limit to the amount of mobs it will spawn, so it wont really not spawn anything by leaving the entity inside the unloaded chunks, like it waits for the chunks to be loaded to spawn the entities.
but wait, that means there will be a runinterval that detects the loaded chunks, which is not great for TPS, so i think ill just remake the idea or something
yeah, i just tested it out, the way it spawns those entities are just too bad, so i have to remake it completely.
has someone managed to do a right click run command on item that can spare some code?
import { world, Player } from "@mincraft/server"
world.afterEvents.itemUse.subscribe(({ source, itemStack }) => {
if (source instanceof Player) {
switch (itemStack.typeId) {
case "minecraft:stick":
source.sendMessage(`${source.name} has used a stick!`)
return
}
}
})
Okay, if im reading correctly... This is to stack an item after it was used, am i correct?
This sends a message to a player that they've used a stick.
Oh ok, hmm, there is a way to replace sendMessage with running a function or not?
Like the idea i have is creating a magic system that uses a staff as the running object and depending on the offhand item it runs a different spell
runCommand
But you should really just read the documentation to see what you can do with what
Thanks, im really trying but its hard to see which custom component to use
Not everything is a custom component
It isnt?
No wonder why i was lost
Understandable, things are a little hard to understand at first but its really good your addon when you get the hand of it
Yeah, tbf i had no idea of scripting until like 2 weeks ago...
Late to the party, I see (I was too but we all got to start somewhere)
Want an explanation of the way these things work
By these things, I mean events, custom components, classes and objects?
Yes! Please 😭
Im so lost now
okay im here... i have to replace surce.sendMessage with runCommand right?
Yes
import { world, Player } from "@mincraft/server"
world.afterEvents.itemUse.subscribe(({ source, itemStack }) => {
if (source instanceof Player) {
switch (itemStack.typeId) {
case "magic:elemental_staff":
source.runCommand(`say test!`)
return
}
}
})
Did he hit his had?
with this i can then make it run a function and in the function create all the different cases
hit his had?
i am refering to the gift you send
Basically:
- Events are listeners that set of when subscribed to with code used. They come in the form of either a
beforeEventor anafterEvent, which run the code either before or after the actual event occurs in-game. If using aBeforeEventthere is the chance of being able to cancel the event from occurring, which would stop the effects of the event from happening. For example, canceling theitemUsebeforeEventwould prevent an item from being used - Custom components are simplified events, of which you can access event handler functions, like
onUse, and work in a similar way to events, designed yo be more beginner friendly and more reliable (so I've heard) - Classes are representations of the state of any given thing in the game. A thing being sonething like items, the world, blocks, dimensions, players, and more (those are some of the most important ones, though)
- For each of these classes, an object is the actual instance of said class, for example, an object of the item class is a real item, an object of the entity class is a real entity, an object of the player class is both an object of the player and entity classes, since the player class extends/adds onto the entity class
oh! thanks that helps, now it makes more sense now
i have another question then, is possible to add another event in here right?
in this case to add cooldown to the object im using i would need to link it with world.afterevents.itemuse?
oh wait...
No need for the other event BTW
yeah i realized, what i meant is that if its possible to have another case type with another item
in the end i didnt needed it, but how can i add a cooldown to the magic:elemental_staff item?
Should I use arrow functions or normal functions?
I usually always use arrow functions but don’t know why exactly, I just took the advice lol
I use arrow functions for higher this use-caseslike inside a class.
It depends on whether u wana use argument or this keywords
i treat it for scope preferences
One major disadvantage to arrow function literals is they have no assigned name. Across larger projects or larger teams, it may not be as easy to navigate stack traces when they frequently say at <anonymous>
Arrow functions have their use yet IMO they are best saved for either object properties (being more like lambdas) or for preserving the this callsite (for classes and similar cases)
Hi again, so after the help with runCommand i managed to advance a lot on my mod! The only thing left is... How can i add a cooldown... Accidentally... Made a super op attack named "Extermination light" that people can spam ._.
use dynamic properties to set and retrieve their cooldown
if they do have a cooldown, cancel the extermination light
for cooldowns use "Date.now()" to get the current time and add "Date.now() + (1000 * cooldownInSeconds)"
Date.now() returns the time in miliseconds of the server. So when the player uses the item you set the players dynamic property to the Date.now(), but you will have to add the cooldown to the overall time. so Player.setDynamicProperty("cooldown", Date.now() + 1000 * cooldownInSeconds).
Once the player tries to use that item, you check using Player.getDynamicProperty("cooldown") if Player.getDynamicProperty("cooldown") < Date.now()
@native osprey
yeah
@minecraft/server-gametest still experimental?
Overcomplicated, just use native component and operate around it
Yes
Bruh.
I’m building something very cool, that many players wanted but other add-ons couldn’t give. 👀
And what is it?
Lemme send a video
video’s here: #add-ons message
Okay i added the component to my item but i still see no cooldown, perhaps i need to link it to the script in main.js?
What do you mean by link?
like do i have to add the runCommand script to the cooldown category?
You mean, to trigger cooldown?
that, yeah
Uhh, this is incorrect
"minecraft:cooldown": {
"category": "magic:elemental_staff_cooldown",
"type": "use",
"duration": 0.8
}
Category is a namespace of this, "use" that you've provided should be in "type" field. Just copy it and should work fine. I think you just need to check if cooldown is over 0
So in this script, you just have to check for cooldown:
import { world, Player } from "@mincraft/server"
world.afterEvents.itemUse.subscribe(({ source, itemStack }) => {
if (source instanceof Player) {
switch (itemStack.typeId) {
case "magic:elemental_staff":
if (source.getItemCooldown("magic:elemental_staff_cooldown") > 0) return
// This code will only trigger, if cooldown has passed.
source.runCommand(`say test!`)
return
}
}
})
im trying but now it doesnt let me use the item at all
it doesnt show errors or anything, it just doesnt run the command
"format_version": "1.20.50",
"minecraft:item": {
"description": {
"identifier": "magic:elemental_staff",
"menu_category": {
"category": "equipment"
}
},
"components": {
"minecraft:max_stack_size": 1,
"minecraft:icon": "elemental_staff",
"minecraft:glint": true,
"minecraft:allow_off_hand": true,
"minecraft:damage": 5,
"minecraft:cooldown": {
"category": "magic:elemental_staff_cooldown",
"type": "use",
"duration": 0.8
},
"minecraft:can_destroy_in_creative": false,
"minecraft:durability": {
"max_durability": 1080
},
"minecraft:repairable": {
"repair_items": [
{
"items": ["amethyst_shard"],
"repair_amount": 270
}
]
}
}
}
}```
world.afterEvents.itemUse.subscribe(({ source, itemStack }) => {
if (source instanceof Player) {
switch (itemStack.typeId) {
case "magic:elemental_staff":
if (player.getItemCooldown("magic:elemental_staff_cooldown") > 0) return
// This code will only trigger, if cooldown has passed.
source.runCommand(`say test!`)
return
}
}
})```
3 backticks (`)
Copy paste like this:
```js
cide```
@round bone i exposed the database i think its all secure
uses jwt keys for read perms and a seperate one for read AND write https://panel.g07hn.com/players
hopefully no one can access or write to the data
Someone said it didn’t work properly so 🤷♂️
So... Any idea?
Can you log the outcome of "getItemCooldown()"?
The black message it shows?
i guess ye
anyone have a working A* algorithm? i had problems with the one from nox7
Is there a way to call a scriptEvent without using commands? I've never used it before.
Other people even upvote my solution, just claim that your is overcomplicated for no reason
👏
Do you refresh these keys?
You don't really have to tbh, if you have a constant key that you'll change every single few weeks, it should be already fine
i mean i can
its super simple but eh
if anyone somehow gets access they will need to find both jwt so
It's pretty easy to secure a server, so don't really mind about these things
?
what
for dimension.playSound(sound, location, {pitch: }), what is the default pitch, and what are the ranges, i cant find info on it anywhere..
You can omit them.
Default pitch is 1.
Default volume also 1.
Ranges are defined in sound_definitions.json
Ik if i am going for default I can omit, but i am having 4-6 noises play that are the same sound and i want each successive noise to be slightly more pitched up than the last.
O, I see.
You need the command
What would that even be good for
System.sendScriptEvent
Nope, you can simply use a method from System class :p
Damn
News to me
It has been there for a while IIRC
But you can execute the command also.
In simple words, it’s possible to call command if you can call that method.
how lightweight is dynamic properties?
is it a bad idea to use getdynamicproperty() every tick
ye
Yep, you should use a Map or Object (with Object.create(null) for dictionaries)
alr thanks
is it same case for scoreboards if i use getscore
Yes, try to reduce API calls as much as you can
It depends on the usage as well, using native methods is always better
How do i create my own custom unicode charecter
@strange marsh if you have time to look into this
I want to use it to transmit data between scripts from different add-ons.
Ty
Yes, but not a necessity to chase microseconds.
I just assumed if someone can’t call a command, then they cannot call sendScriptEvent
Native method has a higher range of usage
Also, it's always better to use native methods
Wydm "higher range"
Y mean more customisablity?
Only if it’s not taking you 2 hours or not requiring you to make a one-liner huge
If you'd like to call e.g. /scriptevent via runCommand without binding it to any entity, block etc., you would have to get a dimension first
Just wrap it around a class/function to re-use it later
There are some samples on #1067535712372654091 also
does anyone know why bds is corrupting my worlds?
i made a void world and applied it to the server but when i join its just a default vanilla worldf
every single time i put a world on it
Can you tell me step-by-step how do you apply your world?
i got it working
i had to zip then download it
Nice
but now my endstone is messing up
it says its running on endstone yet the SDK doesnt wanna work
What do you mean by SDK? Endstone API plugin?
no they have a script api sdk so i dont have to use python or c plugins
it just builds on top of bds
u can grab xuid, ip, ping, set boss bars and other things
This error is probably related only to Endstone rather than pure BDS
You also can use regular BDS and have these properties inside your script
wdym??
XUID you can read out of console, bossbars are possible via JSON UI, for rest of props you can use a proxy
boss bars are possible via json ui yes but endstone has client sided ones
which i need for displaying stats
Show me the error
Is it one related to permissions on windows?
This error is so annoying
All I get is this error when trying to use the ScriptSDK on Endstone
Yea had this issue too
Someone said use docker but I installed Linux instead so yeah
I wish endstone wouldn’t be that dead support-wise
no it was just not using my sdk
but i found out what was wrong
Yeah I used docker and for whatever reason it killed my internet connection on my computer
Not sure how it corelates to that but somehow it was slowing my speed down so much it made my PC unuseable until I uninstalled it
All Good. Seen that conv in endstone server a minute ago lol
Weird. Maybe could you try a VM?
It would be harder to develop using it but still better than nothing
Is it possible for me to make an entity catch fire via the API?
yes
Documentation for @minecraft/server
bruh
I thought it was something more complex.
is there a way to get the texture of a specific item even if it is in another addon and put it as an icon to the buttons inside forms?
Finally done, sorry.
Docker is kinda unusable on Windows tbh
Yeah, I wouldn't recommend it lol
hey does anyone mess with simulated players? i cant get mainhand and offhand to update correctly (or more accurately, automatically) as even if its inventory is full nothing appears in the mainhand unless I reload the world.
no
why not? it's all just resource packs right.. forms can read from any resource pack lol
it is like this, you can use any picture from my pc, just give me the full relative path and i will handle it
you can't know the texture path from script api
what?
if they meant pulling the texture from an item then sure you can't do that but just putting a texture from any resource pack is fine
yes that what he asked for
🤷♂️
i guess you could use json ui
oh actually true.. if you use aux ids lol
Does anyone know why the subscribe property isn't being read when I use this line? I want to display ranks and such when a player sends a message.
mc.world.beforeEvents.chatSend.subscribe(eventData => {
Do you have beta apis on?
Hmm no, I only have version 2.1.0 on Minecraft/server
That's your issue.
And I activated all the world's options
Use beta apis and the beta module.
How do I still getBlockFromViewDirection() even if its air with maxDistance of 10, I just want to get the location to what my cursor is pointing in certain distance
DO you want to use https://stirante.com/script/server/2.4.0/classes/Entity.html#getviewdirection instead?
Documentation for @minecraft/server
Just basic math and algorithm

I am checking before i commit into an idea i end up scrapping, can we get and set mob equipment? like the weapon a zombie is holding?
Via runCommand.
I kinda need to get the item type and durability of the item, change the durability and return it to the mob.
so commands won't really work for me
Then no.
most likely a no, but is it possible to force a mob to swing their arms? not by playing a custom swing animation
like the java swing command
There is the hasitem selector argument. It can query item ID, slot, amount, and data value. Though it doesn't sound like it is very useful in your case
i know, while data is the durability of the tool, the item will still lose its enchantments if i use that
Aye, enchantments on non-player equipment seems to be a rather big hole in Bedrock tech right now
it's a simple class inheritance that could fix the problem but they still didn't do it
What happened to dimension.getGeneratedStructures()?
its in beta.
I am damn sure i read in a changelog that it was released
nope
last time it was mentioned is in .120 experimental section
Hey @distant tulip, could you please send me your replaymod pack that includes entity riding and other stuff?
hey, sorry for the late reply
sadly that part of the development was lost, if you are working on something similar, maybe shoot me a dm and i will see if i can help or point out how i did some things
are the inventory events in here yet?
or something where i can get the item they pickup
Inventory change? Yes
in beta api?
No
inventory is in beta
Can getComponent be used with actually minecraft block components like material_instances and redstone_consumer
No. You can only get custom components or the provided blockcompinents exposed with the api.
Anybody knows how to know if a player is in “i-ticks”? Ideally for how long too.
I-ticks are likely the Invulnerability Ticks, that Red state when hurt.
In a script
I hate quickjs 😔
quick?
That's how the engine is named
InventoryChange? It isn't
it is
How to make a Splash potion of instant health II ItemStack?
inventory change event is in stable
@fallow minnow
i used it in a stable project, not sure what are you on about
i said prety sure wasnt exact
that is not how "pretty sure" work but alright
i see
im having some issues
im just trying to detect certain items the player picks up and re name them
but some of the items error
like when i drop cobblestone its fine
but when i pick it up it errors
yeah its weird
i need to detect the picked up item
any one know where can i found the exact same behavoir files for the vanilla pickaxes?
world.afterEvents.playerInventoryItemChange.subscribe((data) => {
if (!data.beforeItemStack.typeId || !data.itemStack.typeId) return
console.warn(`${data.itemStack.typeId} picked up`)
if (SELLPRICES.find(v => v.id === data.itemStack.typeId)) {
const price = SELLPRICES.find(v => v.id === data.itemStack.typeId)?.price ?? 1;
const mutationLore = data.itemStack.getLore()?.find(lore => lore.startsWith("§")) ?? null;
if (mutationLore) {
const invisibleId = mutationLore.split(" ")[0].split("").map(ch => ch.replace("§", "")).join("");
const mutation = MUTATIONS.find(m => m.id === invisibleId);
if (mutation) {
const finalPrice = Math.floor(price * mutation.multiplier);
data.itemStack.setLore([`§f`, `\uE141 §r§v${finalPrice} §7each`]);
}
} else {
data.itemStack.setLore([`§f`, `\uE141 §r§v${price} §7each`]);
}
}
})``` i just get cannot read property typeId of undefined
?.typeId
beforeItemStack can be undefined
and when dropping an item, itemStack can be undefined
okay that fixes the error
but
when i drop it doesnt log anything
i dont get a "picked up"
the top guard clause should different then
How does the volume property work for entityQueryOptions? I'm trying to use it to get entities to remove, but it returns a empty array
const removedEntities = overworld.getEntities({volume:cosmetics.from, location:cosmetics.to, excludeTypes:["minecraft:player"]})
its like dx
guys can anyone briefly explain how custom components work?
from my perspective, it's just like a frozen json object where u can only read it's contents (string, number, boolean)
which is defined in .json
U have to register a component in a script, like this:
```js
system.beforeEvents.startup.subscribe(startup => {
startup.blockComponentRegistry.registerCustomComponent('my:custom_block_component', {
onPlayerBreak: ((data, params) => {
data.player.sendMessage('You broke ' + data.block.typeId + ' with params: ' + JSON.stringify(params.params));
})
});
});
then, when you're making a block, in it's components u need to add your component, for example:
```json
"components": {
"my:custom_block_component": {
"param1": 1,
"param2": [1, 2, 3]
}
}
```
then u can add some events in component (in script) and if a block has this component, it will trigger the events. All events u can find here: https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/blockcustomcomponent?view=minecraft-bedrock-experimental
And u also can use the params, that u specified in json
truly a custom component
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]
adding this here Block Custom Component
reveal? What is it?
just some object crawler
Society if Mojang increased the depth limit.
Why does it even exist
thankuuuu
is there a function or something that lets you cause explosions and control their power
and like when are we getting an event that listens for crafting bro 💔
YESSS TY
np
lol
damn, using blocks instead of JSON UI to display UI is 🔥
i orginally planned on using some ui for it when i made it, but i cant do json ui so i was cooked 😭
also its not using script api
The json ui thing I can accept, but doing it without scripting is just psychopathic
Script api is too slow for the cpu emulation
but how does it work then?
Sounds fair
oh
Say that from the start, I was worried for your mental health
When I tried on script api first it got about 1.7% the normal speed of a gameboy
It was in script api first but was too slow and i put i on serenity which runs node not quickjs, and it ran 100x better
So my sanity is still gone
But it's functional
is it out of beta?
Wym?
if serenity is out of beta
Oh
Umm idk tbh
I didnt know there was a "beta"
Its constantly updating but has beta releases like script api does, stuff that is in testing before stable
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]
Well I checked serenity once, months ago if not nearly a year ago and it said it was in beta, idk will check it out
I just need some help with this formula, I want to increase the view distance by atleast 5, afterany tries I still dont know how.
If possible, how do I make it detect the nearest block in range instead of bypassing it
export function blockFromView(player,prop){
const lastPlace = player.getDynamicProperty(prop)
if(!lastPlace) return;
const viewDir = player.getViewDirection()
const headLoc = player.getHeadLocation()
const facing = {
x: (headLoc.x + viewDir.x),
y: (headLoc.y + viewDir.y) - 1,
z: (headLoc.z + viewDir.z)
}
return player.dimension.getBlock(facing)
}
You could just use getBlockFromViewDirection could you not?
That will not detect air tho
But I've tried to do both functions that if getBlockFromViewDirection failed, it uses getViewDirection instead
in pistonActivate afterEvent, when does piston.isMoving return false?
2 game ticks later, figured it out
Script API
I have a duration parameter in my custom command, should I have it in ticks or in seconds, and should I specify the format in name like "Duration in ticks"?
Depends
ticks probably.
what's the best way to check if a slot in the player's inventory is empty? my script keeps crashing because it "cant read property 'typeId' of undefined" when the slot is empty :(
check if the item is undefined in the slot.
is this correct?
if (item.typeId !== undefined) {
return (item.typeId);
}
just do
if (item)
tysm, it works now :D
idk how it was crashing though
[Scripting][error]-TypeError: cannot read property 'typeId' of undefined at itemMainhand (main.js:58)
at jjkTick (main.js:18)
this was the crash log
well, thats not a crash
the entire script stopped working after though?
I thought you meant crashing your game/world.
what should it return if undefined?
return("");
return item?.typeId ?? ""
compact
well, that's how itemStacks has been anyway
nice, ty
Most of commands are using ticks, so I'd stick with ticks
why is entity.getRotation().y always 74.51033...
i want to get the block the entity is looking at but the result of getBlockFromViewDirection is incorrect
so i am trying to calculate it myself but rotation is also incorrect
entity.getRotation().y seems to return the rotation the entity spawned facing
Use getBlockFromRay and add 0.1 in y-axis
tried that it's bugged
define bugged
this is the only solution that worked for me
the raycast of the entity only updates when i hit it
it returns undefined if there's no block.
I guess u already knew that??
i know, for example if i hit the entity and place a block if from of it it detects it, but when the entity turns around it still detects it until i hit it again
I dunno then, I never had a problem with ray casting
are u using view direction or rotation?
for players maybe but for entities it's bugged
Don't need to send it twice bruh
this returns the same thing as getBlockFromViewDirection
wdym?
the ray will just create a ray based on params you put
ok...
obviously but what I meant is the value you put itself
try to create a particle ray using the direction of the zombie facing
what value do i put? getRotation is bugged also
here...
how do i get the direction?
getViewDirection
the one ur using here
i already know the result but i am trying it anyway
yeh, I just want to know if the direction is actually correct
maybe when an entity turns the view variable you used isn't updated
I can't think of anything to why wouldn't ray casting work properly unless the params put is broken
this is getting the entity every 18 ticks
even relogging doesn't change the view direction, it's definitely bugged
commands it is
then it's the getViewDirection and getRotation not the blockRay
Send codeblocks instead screenshots, it helps a lot for helpers
oh btw, use ruInterval and keep checking the view direction value
if it's actually not changing if they turn, then that's the problem but if it does, then it's how you set it up is the problem
it's more difficult for me, i use discord on mobile and vscode is on my laptop, i am used to sending screenshots over a usb cable but sending text is more difficult
i have discord on laptop but i don't launch it on startup to save battery
Interestingly x and z are changing when the entity turns but only the value and not the direction, y is not affected which suggests that it's internally using getRoation().x (vertical) and getRoation().y (horizonal) because the vertical rotation works perfectly there also but the horizontal isn't
hi there! have mojang made any change to the item consumption after cooldown ends? something is happening to my when I use a item that has cooldown it is being removed when the cooldown ends
A script to make me backflip (irl pls)
Never Mind even this isn't working!
how can a man get which block a mob is looking at???
what type of entity are u using?
zombie villager
but it's not specific to it, all the entities that i have tried also suffer from this bug
weird
except player
what version do u use?
I mean, API version
it wouldn't matter because even the command using ^ ^ ^ doesn't work
what is preview only?
yeah
have u tried creating new world?
in a new world, i ran the command to spawn a particle at ^^^1
the x and z direction only update when the entity spawns, moves or gets hurt, but the y direction updates immediately when they move thier head
i am wondering if molang queries would work
Hello! Do I need to install npm to run script api inside of minecraft? It's throwing an error of not finding "@minecraft/server"
u don't need to use npm, it's just to see types, when you're coding.
and show manifest.json
there should be a dependency with server module
Like this
@pearl waveshow full manifest
hmmm
is it possible to give myself a spawner with data already in it without using structures
like a cow spawner
nope
and where is the dependency?
actually i might know a way
getComponent doesnt save the mob
what am i saying
can i set blocks with certain data?
depends on the data
Ahh, thanks for the help! I didn't notice I had the wrong folder open in vscode... Thanks alot!
i just want to set block a spawner with a mob already in it
then no
use structures
@fallow minnowwhat u making now
why do u need so many spawners?
because they are for different mobs
I know, but what is your goal?
if only they give us nbt...
what do you mean??
I mean why do u need a spawner for every mob?
my goal was to get mob spawners with data already on them without using structures
even molang queries didn't work 😭
i am done. it's just impossible
what are you truing to do @buoyant canopy
get the block a zombie villager is looking at
Get block from view don't work?
well the mob spawner doesnt just spawn every mob.. so i need spawners for each mob
You can make a system run for that with some checks when you place down a spawner set a dynamic property for it
I kinda did something similar
ehhh yeah im trying to steer away from that
i was thinking of like
giving them a spawner with invisible lore on it ( not stackable ) which determines the type, then i just have structures that load when i place the block to replace it with the correct type
it doesn't, neither is getViewDirection, getRotation, commands, nor molang
Is there any way to detect which face a block has been mined on?
oh yea thats smart. You can also add a tag or something to spawners in itself
zombie's view direction is broky-broky
Unfortunately, it’s not possible.
However, you can save a js file and load it dynamically using import() function
Can’t mid game
It’s a ES standard. It shall be possible.
Do u mean cant..?
Hello May I ask a Question here but erm can you Use Get Component for Potion effects or some way? In beta or stable
Nvm
there's a potion class
Shall = must. Think will + must.
My statement is that “dynamic imports” are a ECMAScript standard, so they must be possible in the game.
hi
hey
can i add xp to someone without summoning it and using run command
Nope they have to be in game
You could make a dynamic property that stores it and give it to them when they join
Documentation for @minecraft/server
The player has to be online for that or it returns an error prob like not a function of addLevevels of undefined
OP never clarified the player has to be offline.
Quick question, is there any tool to help with development? I want my BP and RP to be in the same file and export it to the right folders
Hmmm i will definitely look into that
huh
Are you using 2.4.0? Are there any other NPM types added?
It shouldn't. Do you have any other NPM types installed?
nope just these
Is there any conflicts? I know there are times where installing server-ui meant the server npm types got outdated.
soo do i just uninstall all node modules
{
"dependencies": {
"@minecraft/server": "^2.5.0-beta.1.21.132-stable",
"@minecraft/server-admin": "^1.0.0-beta.1.21.131-stable",
"@minecraft/server-net": "^1.0.0-beta.1.21.131-stable",
"@minecraft/server-ui": "^2.1.0-beta.1.21.131-stable"
},
"overrides": {
"@minecraft/server": "2.5.0-beta.1.21.132-stable"
}
}
``` i uninstalled server and added ovverride then installed it back and i still dont get the correct things
i deleted my node modules now all types are fucked
after re installing
yeah im reverting back to my other node modules, i dont need addExp that bad
not until they fix their shit node modules
I mean, you can always just use it without the types.
true actualy
Or add it directly to the Player class thats what I do when I know it is a thing and not showing
Summon creeper -> trigger the event to apply the component. You can check the files for the exact event.
yall think playerInventoryItemChange is supposed to trigger everytime on /reload or does it make sense to?
for my script its usefull doing that but if its not intended and it could be "fixed" one day id rather change it now
I can't recall, but does it trigger on worldLoad?
Last I recall it did. And it triggers once for every item in the inventory IIRC
I'm guessing when the player loads or the world loads into the world, the item in that slot is changed or added from previously stored data
but i could be wrong
I have a lot of dynamic properties being read and written for a stats addon, does anybody know of any resources that could point me towards better efficiency?? Ive read that using a map to cache the data and writing it to the property at a later date is better??
Use scoreboards? That's what they are made for after all. If it's about stats anyway
Also sure, map will be more efficient if you save stuff in a smart way (risk loosing data on server shutdown or crash)
dps are more efficient I think
Can you read from a scoreboard with scripts?
Does the damage cancel stop players from destroying armor stands?
Yes; world has a scoreboard property that lets you grab info on them
You can access this via:
import { world } from "@minecraft/server"
// And all methods/props etc. will be there
world.scoreboard
const form = new ModalFormData()
.title("Add Bounty")
.label(`§fCoins: §e$${getScore(player, "Coins")}`)
.dropdown(
"Select player to add bounty on:",
allPlayers.map((p) => p.name),
)
.textField("Enter bounty amount:", "e.g. 100");
form.show(player).then((res) => {
if (res.canceled) return;
console.warn(parseInt(res.formValues[1]));```
im pretty sure this used to work fine
idk whats wrong
the API counts .label or .header as element, so the indexes of following elements are shifted
ohh ok
well, u need to get res.formValues[2] instead of res.formValues[1]
is this a new thing?
this is because u use .label
ah ok
in this case u can use .body
Anyone know why this specific new Date() doesnt wanna work? If I put anything inside it (ive tried nothing, any kit value, any number), it crashes the world. but removing it works fine.
I have a custom command, but it uses logic in system.run using ModalFormData and it can’t return a CommandStatus instantly. I get an error in console.
It doesn't mess with functionality, but when I want to error, it doesn't let me.
Shall I use await somehow?
how to check if a string resolves to a block id?
preferably without commands or try catch
store a map with all valid block ids
surely there is a better way
I found the issue, turns out the return message for commands are limited to 512 characters
if (BlockTypes.get(id) != undefined)
for dyanmic properties is it 8MB total across every DP in the world including item DP's? Or is it only ones saved to the world.
who told you that there is a 8mb limit
I was told that ages ago ive never really fact checked it, is that not the limit?
by ages ago i mean like 2 years ish ago
its just always been in my mind
there is no limit afaik
unless you hit the key limit
and that is kinda imposible
key limit is 32k im guessing
there is a warning when writing stuff to fast, bu that is it
oh weird, im not sure where i got that 8mb max from its just always been in the back of my mind
you get a 10mb warning iirc
10mb was saved last minute or something like this
yes and no
you will need to look into how many different key you can make out of 32k
it is not just 32k key
ohh gotcha, im just saving player data, so each player will have their own DP with their json Data, and i have alot of other databases so just wanted to make sure, i dont think a whole 10mb will ever be saved in the span of a minute though
you shouldn't worry about it
i had a project where i saved more than 1 dp per tick for 20 minute with no problem
gotcha, thanks
just keep performance in mind
Hii
I was reading the v2 api changes to update my scripts and optimize them, i havent tested anything yet, now i can run block related operations during worldLoad right?
During v1 i used to use ``fillBlocks()` after playerSpawn was fired
Chunks still need to be loaded.
I see, what about preloaded ticking areas?
I have not messed with those so I have no idea.
how can i get the players view direction in 90 degree intervals
What does that even mean?
like normalize the view direction into 90 degrees
like north is 0, east is 90, south is 180 etc
I see
-180 to 180, or 0 to 360?
I didn't understand what you meant by interval in degrees
Just use player.getRotation().y
because i want 90 degree points instead of precise rotation
ummmm 0 to 360
oh wait i see your question now
So the closest cardinal point?
my memory is foggy so i dont know if .getRotation() does 0 to 360 or not
gotta test that out
(not me though)
I think it goes from -180 to 180
ohh wait yeah i meant rotation not view direction oops
So again, let's say you have 80, you want it to be round to 90, or 15 to 0
Is that correct?
but yeah basically i have a particle that i can rotate via variables and im just trying to rotate it 90 degrees based on where they were looking towards
like itll always rotate correctly facing them
instead of being in a static state of 1 rotation
But there already is a look_at_xyz property for particles
I think that's what its called
So I have an idea for a food addon that uses only pre-existing ingredients. No adding stuff like tomatoes, onions, and lettuce. Only adding onto what is already there. Its probably going to be the most complicated thing i ever attempt with blocks, because i aint touching entities. So to start wit...
yes ik but im going for something else
something ive been thinking about recently
You want the particle to only align with the owner's rotation?
a lock icon appears on the block telling the player they cant break it but currently it has a set rotation, but if i go to another side it is still facing that wrong direction
like if i break it from that side it should face me
I see
so i need to get the rotation or whatever it is
Wait me a minute
i already have the particle all set up for rotations but i just need the script side of it
idk what to use
and here is about the best place to put it
wrong reply but it frankly doesnt matter
Who?
go7hn
Oh
at first i was going to make a fake block particle but
i got it down
and its just
too much
it would be like a locked outline thing so im just doing this
ok so instead of getting player's view direction, we can instead go by getting which direction of the block the player is at
like the face?
close enough
I think this should work
function snapYaw(yaw) {
yaw = ((yaw + 180) % 360 + 360) % 360 - 180;
const cardinals = [-180, -90, 0, 90, 180];
let closest = cardinals[0];
let sDiff = Math.abs(yaw - closest);
for (const angle of cardinals) {
const diff = Math.abs(yaw - angle);
if (diff < sDiff) {
sDiff = diff;
closest = angle;
}
}
return closest === -180 ? 180 : closest;
}
I can be simplified a lot for sure
@fallow minnow
if you subtract block's location from player's location, youll get the direction of the player from block in vector
it should be similar to block's face location from there
Ok I reduced the lines
yaw = ((yaw + 180) % 360 + 360) % 360 - 180;
const cardinals = [-180, -90, 0, 90, 180];
const angle = cardinals.reduce((a, b) => Math.abs(yaw - b) < Math.abs(yaw - a) ? b : a);
I don't know about particles, but I think they use yaw instead of vector?
Again, Idk anything about particles
yeah but we dont really need to get to the angles since we only need to snap it by 90'
im just snappig by 90'
which one thing weirdly happens
it only supports 90, -90, 180, -180
yeah thats basically how most programs handle angles
And 0
and 0 yeah
actually
now that you mentioned this
we can just go back to .getRotation()
just gotta handle the snap part
i wish i could test it in game but i cant rn 😭
@fallow minnow
Math.trunc(yaw / 90) * 90
feed .getRotation().y in yaw and try it
THATS IT??
whuh
How does Jayly get what coordinates a player sees?
oh try subtracting by -90
I am too dumb for this
also this math doesnt really have margin of error or something so its gonna be odd when you slightly tilt by right
this is why i first suggested using location to get direction
also i cant help with it too much since i am absolutely horrible when it comes to math 😭
is there a way to check what type of armor trim a player has on their armor
Yummy
.
Throws "Native type conversion failed"
Even in chat
Im trying to add @minecraft/server-net but my servers world dosent have beta api's enabled, how can i enable it without world corruption, and creating a new world? i tried via a nbt editor and after i add gametest to experiments and set all 3 to 1, then restart the server and redownload the level.dat file its still dosent exist
Update: tested it, at least in the latest BDS, it throws chunk unloaded error
Check the native methods you have used, some parameter input is the wrong type
I’m returning js { status: CustomCommandStatus.Success } or js { status: 1, message: msg }
It needs all to happen in one go.
Meaning no awaition/system.run
Least u could do is return when the form is shown without awaiting
form.show(player).then(...);
return {status, message}
but the problem is that I have to manually validate the form, so I can't say success or fail instantly
I guess I will do sendMessage with §c?
After the form show, yeah u can sendMessage
What status does?
Then it’s... practically useless.
its mainly used for command blocks i think
Possible to cancel critical hits and make them normal?
I don’t want to integrate my 18KB i-frame disabled giant with cooldowns.
When I make a mistake in the code, the entire add-on stops working. Minecraft's debugger shows the error, but since everything else stops working, the resulting errors obscure the main problem.
Is there a way to solve this?
You should handle any possible error
Using Try-catch statements, defensive code and..
Or even typescript, that helps you preventing unexpected cases, and write cleaner code
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]
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]
Cancel damage then apply damage maybe?
Yes, preview beta APIs.
Is the command syntax different when you use dimension.runCommand()? This command runs fine when I run it from chat, but the syntax breaks down from the script.
execute positioned ~~~ run stopsound @a[r=50] record.lucas_bowl vs
execute positioned ${block.x} ${block.y} ${block.z} run stopsound @a[r=50] record.lucas_bowl
Hi, i want to get into scripting, and i need a up-to-date tutorial about scripting. Any chance anyone has what im looking for?
whats with this new ddui?
and what has it to do with data driven?
cuz on the docs i didn't see anything related to it
What docs are youu searching?
Look at #1468349958221729823
microsoft one
i mean, does it relate to data driven programming, or am i confusing things?
so has nothing to do with the data driven im thinking
What are you thinking?
data driven programming, cache hits, and stuff like that
i thought it'd be ui with that kind of thing in mind
well, thanks
imma checkout the docs
It's Beta API in Beta Version, so its not accessible (I stay on stable, but I'll changing my mind to previews)
damn, i need a full tutorial for the new ddui, can't even understand ts 😭
How can I use dimension.setBlockType in an unloaded chunk?
I’m trying to use the tickingarea command before calling setBlockType but it doesn’t seem to work.
There is a ticking area manager in the World class
It is async so you have to await it before continuing your process
Oooh I didn’t know that, but I don’t see it in the documentation, did it get deprecated?
What module version are you using?
I was about to say latest (2.4.0) but I see that there’s a newer one (2.5.0) lol.
The ticking manager is in 2.7.0-beta, hmm I would need to enable the beta API in the world settings, correct?
I didn't notice it was still in beta
In that case you can either switch to beta or wait 1-2 ticks after running the tickingarea command
I even give the game 5 full seconds and it still ignores the setBlock function.
I’m trying to make a safeguard to run something at the original position if the player suddenly teleports or changes dimension
I think it might have to do with the game caching the chunk thinking it’s loaded and then ignoring the functions
dimension.runCommand(`tickingarea add circle ${string(previousLocation} 2 blah`);
system.runTimeout(() => {
dimension.setBlockType(etc)
dimension.runCommand(“ticking area remove etc”)}, 20);
Sorry for the formatting I wrote it from my phone lol
The commands always return result.successCount = 1
Is previousLocation a Vector3?
Try tickingarea add circle ${pos.x} ${pos.y} ${pos.z} 2 something true
I think string() isn't even a thing
Also check if the ticking area list is not full
The command has a limit of 10
Yes, string is a custom function that takes a vector and returns ${v.x} ${v.y} ${v.z}
I’m testing in an empty flat world with nothing going on
Isn't string is a reserved word?
Also you didn't close the function
Also add "true" at the end
Don’t pay attention to the syntax, I wrote it from memory xd
But the logic is correct, it does run without any errors but the block doesn’t get replaced
I’m 90% sure is not about the code itself but rather a Minecraft quirk
console.log('Hello World')
Here's the actual code:
console.warn("1");
const unloadedPosition = { ...previousPosition };
previousDimension.runCommand(
`tickingarea add circle ${Vector.toString(unloadedPosition)} 2 ${TICKING_AREA_NAME} true`,
);
system.runTimeout(() => {
console.warn(Vector.toString(unloadedPosition));
previousDimension.setBlockType(unloadedPosition, MinecraftBlockTypes.Air);
previousDimension.runCommand(`tickingarea remove ${TICKING_AREA_NAME}`);
console.warn("2");
}, 20 * 5);
I hopped back to my pc to test and still doesn't work... anyways probably a Minecraft quirk, thanks for the help regardless
That's weird, I used that method before and it worked for me
let tickPos;
let block = dimension.getBlock(current);
if (!block) {
if (tickPos) {
dimension.runCommand(`tickingarea remove "${tickID}"`);
await system.waitTicks(2);
}
tickPos = current;
tickID = `namespace:${system.currentTick}`;
dimension.runCommand(`tickingarea add circle ${current.x} ${current.y} ${current.z} 2 "${tickID}" true`);
await system.waitTicks(1);
block = dimension.getBlock(current);
}
hmmm weird, I'll do more testings tomorrow
thanks for the help regardless!!!
I unintentionally unlocked a new gameplay style XD
How are u detecting key pressesw
looks like third party code
why share it here then
I used websocket
WebSocket is kind of a ScriptAPI, I think.
If not, I apologize for posting this here — there doesn’t seem to be a chat specifically about WebSocket scripts.
You can do a lot of things with it, and a lot of people just ignore it XD.
with server-net right
i kinda forgot that was a thing lol
server-net isn’t fun
WebSocket connects directly to the client.
It’s almost like a mod that can be used on any server
You just need to have it to use it
The tickingarea command has a few issues, but you can work around them in the meantime until the API comes out of beta.
-
The big one is that in my testing if you use the "circle" tickingarea it will keep the entities loaded, but not actually load the blocks. (This might have been fixed since then, but it was definitely true at one point).
-
After you create a ticking area it can take any amount of time to load the chunk. Usually around 5-6 ticks, but sometimes more than 10 seconds. It's best for you to wait until
dimension.isChunkLoadedreturns true. -
When you remove a ticking area with the command it isn't removed right away. You need to wait until at least a tick after the chunk is done saving (when isChunkLoaded starts to return false) before you add a tickingarea with the same name back or else the add command will succeed, but the game will never actually add the tickingarea.
so did you use the websockets api? wasnt it deprecated? i have tried using it before but due to the lack of docs i gave up
I don't think it was officially deprecated, but they have been very clear it's undocumented and unsupported and they might remove it or change how it works at any time so a lot of people don't want to invest the time to do things with it.
It was never well documented, apparently it’s lot used in the Education Edition.
Mojang should pay more attention to it
it’s literally client-side scripting.
It can read a ton of events, but it can only execute commands.
bruh
At least can make a command macro :3
can you share the code? so i inspect it and maybe i generate some docs for it
There’s a PDF floating around somewhere
I saw it once, but it was on a site that wouldn’t let you download it without paying.
I made a simple one using TypeScript.
interface SendCommandWS
{
header: {
version: 1,
/**
* uuid
*/
requestId: string,
messagePurpose: "commandRequest",
messageType: "commandRequest"
},
body: {
/**
* minecraft command
*/
commandLine: string
}
}
The upside is that the site doesn’t block screenshots
I see…
I’ll keep trying, thanks for the info!
Anyone made a system like Hytale where you can mine 1 block together to speed it up/track progress?
Can't believe I found a use for unsubcribe.
does the @minecrafter/server-net api module, have a request limit when talking to a server?
in terms of rate limiting i dont think so, in terms of how much youre sending yes which is watch dog
if you exceed the memory limit it may crash you
but im listening for discord messages and online players through a bot and bridging it with server net every second with no issues
left the server on for hours and no issues
thats pretty much what im doing, i just have a constant connection, and i created a runTimeout where if theres no response itle close the connection to the websocket, and i was getting randomly disconnected, so just making sure it was somthing wrong with the code rather than something else
is it possible to use addEffect() with infinite duration?
Unfortunately no, you'd need a higher number of use runCommand.
There's also an option inside of server's configuration to manipulate how many request each add-on can send to a certain URL
I'm using setCurrentValue for a custom damage system on my addon but with absorption hearts in play it gets weird, it seems like the hearts shown to the client do not match what the server knows
i can right click any item in my hotbar and suddenly, all my absorption hearts are back
and then i just see normal hearts suddenly lower
guys how can i make something for exampl i want to make an ore scanner that scans the area and shows the ores behind the walls but the problem is how can i show them and make them appear behind walls??
Entities with custom materials
anyone else notice that inventory change after event fires upon player join?
meaning the game re-gives their items upon joining
which is kinda cool
i find it quite cool, i use the pickup method thingy for assigning prices to certain items
and for them to update they just rejoin
or just re pick up the item again
Are you talking about PlayerInventoryChange or EntityPickupItem that was recently introduced?
inventory change
and you just use the item not before item
so it only runs on pickup
Make sense
The client don't hold the inventory infos
Armor too i assume
What is the Minecraft server API 1.21.130+?
Any way to get the item entity that is dropped from a block?
Yes.
world.getLootTableManager().generateLootFromBlock(block)
That returns an ItemStack.
It does not return the actual entity instance.
Does return in a OnPlayerInteract stop the player from breaking blocks?
No. Use the player break block before event.
Are you in adventure mode?
No im like something stops me every time I start breaking something
I can break something if it can be instamined
Its my fucking controller 😭
Because I have x to destroy block
And for some reason the game doesnt like that
Ok so I fixed it 
What happens when you dont use return at the end of something like world.beforeEvents.playerInteractWithBlock or something like that
Nothing.
functions always automatically return at the end
hopefully not anytime soon
but they will eventually
but they keep archives for these modules right?
like we still have and can use @minecraft/server 1.8.0.
Oh, try to get it with world.getDimension("overworld").getEntities({type:"minecraft:item"location:block.location, maxDistance:1})
is there a way to make a player glide without an elytra
u can try applyImpulse with slow_falling effect
That wont work as a player can jist drop an item.
what does applyImpulse do
any documentation on that?
Gives speed to an entity in a certain direction
Hmm than no idea
U can use before and after variations of playerBreakBlock to getEntities in beforeEvents and store them in a variable and then in afterEvent u use getEntities again and filter the list to get only new entities
alr tysm
Too many edge cases such as non full blocks.
is saving items in dynamic properties reliable with itemstack
in terms of duarbility names enchants and that sort of thing
also want to know if I can save a big object in a dynamic property with all the inventory slots as keys for an item
Wait what you can change the selected slot with
player.selectedSlotIndex = 9
I didnt know that. I thought it only returns the slotIndex
How can I .nameTag with translate? 😔😔😔😔
I don't think u can
what does getEffects return in duration if the effect is infinite?
if i had to assume
either Infinity
or undefined
or maybe it gets ignored
let me test for you rq
-1 actually
interesting
slowness had a real number, night vision had infinite
i wonder why they won't/can't add infinite to addEffect
anyway
can you set it to -1?
that's crazy work ngl
alright, thanks
i'll test tho
just add the ability to set it as Infinity like...
fr
yup like i said
is it possible to cancel join msgs?
or atleast edit how they look if i cant cancel it
Resoruce pack
yea but how?
/texts/ directory, edit the .lang files
and put what?

nah
Use the vanilla resource pack and download the file and edit it
you can put invisible lines to kinda "cancel" it
I dont know if theres a command to the repo
but i don't recommend that
No
Here
fair enough
k got it
multiplayer.player.joined=%s joined the game
how do u shoot an ender pearl like projectile ?
when i use spawnEntity() and shoot() it gets stuck in unloaded chunks
but if i throw an ender pearl normally it'll land as usual
I think this behavior might be hardcoded for the ender pearl, but you can try adding the "minecraft:tick_world" component to your projectile entity though, it might work but I've never tried it for this.
i tried spawnEntity with vanilla ender pearl and it is also having the same effect, its not loading chunks while spawned with scripts but does when i throw manually
i had to edit ender pearl.json to make it spawnable idk if that broke anything
thanks I'll try , i was wondering if theres any better methodes for shooting projectiles
import { system, world } from "@minecraft/server";
const trackedItems = new Map();
const DESPAWN_TIME = 30;
system.runInterval(() => {
for (const [entity, data] of trackedItems.entries()) {
data.remaining -= 1;
if (!entity.isValid) {
trackedItems.delete(entity);
continue;
}
const item = entity.getComponent("item").itemStack;
let name = item.typeId.split(":")[1] || item.typeId;
name = name.replace(/_/g, " ");
name = name.replace(/\b\w/g, (char) => char.toUpperCase());
entity.nameTag = `§f${name} §cx${item.amount}\n§e${data.remaining}s`;
if (data.remaining <= 0) {
entity.kill();
trackedItems.delete(entity);
}
}
}, 20);
world.afterEvents.entitySpawn.subscribe((ev) => {
const entity = ev.entity;
if (!entity || entity.typeId !== "minecraft:item") return;
trackedItems.set(entity, { remaining: DESPAWN_TIME });
const item = entity.getComponent("item").itemStack;
let name = item.typeId.split(":")[1] || item.typeId;
name = name.replace(/_/g, " ");
name = name.replace(/\b\w/g, (char) => char.toUpperCase());
entity.nameTag = `§f${name} §cx${item.amount}\n§e${DESPAWN_TIME}s`;
});```
ive had this system for a while and i wanted to change it to display the items "display name" instead of the split up typeId
possible?
nameTags don't support rawtext, so no :(
but like
no possible way at all
to get the items name?
like named in an anvil say
Well, unless you transfer all the names from RP to BP, but that won't support custom items
bruhhh
how do I check what type of armor trim is on an armor piece in an itemStack
is there a way to make a vanilla block a ghost block? so just make it so people can walk through it basically
that's.... not even a script related problem...
no afaik...
really? I wanted to use this in a playerPlaceBlock afterevent
what do I need to do for this to work then
vanilla blocks are data-driven
you can't modify them
either you give up on that idea or create a custom block having no collision that looks exactly with the block ur trying to make "ghost block"
its supposed to work for every single vanilla block so cant really do that lol
thanks anyways
or make a custom entity that makes the item it's holding animated to position like a block
not really perfect but almost there
If i change a block state's name, will old versions of it change or?
I don't think so
if (item.typeId === "ocp:set_sequence") {
const checks = [
{ scores: [0,3,4,0], func: "omnip_decouple" },
{ scores: [4,4,6,2], func: "unlock_feedback" },
{ scores: [3,4,1,1], func: "unlock_upchuck" },
{ scores: [1,2,1,9], func: "failsafe_off" },
{ scores: [3,8,2,1], func: "failsafe_on" },
{ scores: [0,0,2,3], func: "unlock_iguana" },
{ scores: [9,3,9,4], func: "unlock_blob" },
{ scores: [7,3,3,7], func: "unlock_fungal" },
{ scores: [3,2,6,7], func: "unlock_eyeguy" },
{ scores: [1,0,3,4], func: "unlock_buzz" },
{ scores: [0,4,0,0], func: "destruct_timer" },
{ scores: [9,0,3,6], func: "unlock_master" },
{ scores: [7,0,8,4], func: "unlock_playlist_two" },
{ scores: [1,4,6,0], func: "unlock_idem" },
{ scores: [5,5,3,1], func: "unlock_spitter" }
];
for (const check of checks) {
player.runCommandAsync(`execute if score @s default_one matches ${check.scores[0]} if score @s default_two matches ${check.scores[1]} if score @s default_three matches ${check.scores[2]} if score @s default_four matches ${check.scores[3]} run function ${check.func}`);```
Hey guys,is this well structured?
nah
first move the array outside the event loop
second runCommandAsync has been removed
use runCommand instead
third, use scripting API's native scoreboard feature
in action data form can i display a variable for the body of ui instead of message?
depends
is that variable a string?
if it is, then you can
ye
then you can.
like .body(variable)
yeah it'll work just fine
fourth: i have a feeling these mcfunctions you have can be replaced by scripting API js code
but aye it ain't my business
i recommend you use this wrapper instead of using the API directly: #1398563867042381905 message
but you're welcome to use the API:
https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.Scoreboard-1.html
(accessible via world.scoreboard)
do i need server ui for onscreen display component?
no
just use player.onScreenDisplay.method
Exmample: player.onScreenDisplay.setActionBar('hi')
i see
is it possible to add custom textures for the player.onScreenDisplay?
what do you mean?
using json ui
what????
player.onScreenDisplay isn't a real ui element
do you mean the actionbar?
player.onScreenDisplay.setActionBar('actionbar lol')
or what exactly?
i wanna add a custom png using json ui on the player screen. is it possible with onscreen display?
you mean a hud element on the player's screen like the attack button for example?
if that's what you mean, then idk
it's probably possible but it'll be very JSON UI heavy and will be complicated as heck
player.onScreenDisplay doesn't give us an option to render a custom hud element.
oh
do yk any way for a custom hud element to render?
nah man
honestly my advice: whatever the hell you're gonna do with a custom hud is NOT worth it
onScreenDisplay is a class used to access other functions such as setTitle and setActiobar
it doesn't relate to json ui in it's own
it'll probably be very complicated, glitchy and laggy asf