#Script API General
1 messages · Page 94 of 1
did they change the OnPlayerDestroy() customComponents on blocks?
this is a better way lol
Perfect, it's working now, sorry had a lot to convert over to that method before I could test what i did wrong.
Thanks Sprunkles
Oh haha ok, I'll use that then. does it really take up more memory?
my OnPlayerDestroy doesn't get triggered somehow
idk but i think its alot better
K, it definitly looks simpler. Thanks again!
yup
onPlayerBreak i think
Anyone got better docs than the Microsoft ones?
Need it for Behavior and Resource packs
Bedrock samples?
How to make 2 different server_from parts not conflict and cause errors
I meant more doc-like, not juet pure data without any comments or explaination how to use it
Unless you’ve already checked https://bedrock.dev I don’t have any suggestions
Thanks, seems to be a good Site
Jayly's doc have examples
Imagine putting runInterval inside OnTick, could be me.
onPlayerBreak
yeah
Please, do not do it
😭
Unless you'll clear it
manipulating the itemstack.amouny doesn't work somehow
it still prints the amount
playerItem.amount - 2;
sc.print(playerItem.amount)
playerEquippable.setEquipment("Mainhand", playerItem);
nothing changes somehow
Problem. You didn't actually set it
what did I miss?
Use -=
I solve tons of big problems in this code yet I can't even spot this kind of issues
exactly
I'm guessing the debugger can't be used on realms?
Nope
RIP
I have a realm that's lagging massively and I'm not sure if it's the addon
1 player out of 10 and it's getting like 5 TPS
The addon works fine locally, I assume it is just bad servers. The world file can't be downloaded as it's too big
Bedrock shit then
is there a way to run a command as the server instead of a player?
like world.runCommand() or smth
world.getDimension('overworld').runCommand()
ok
if you already have the player reference it is better to do player.dimension.runCommand
is there a way to modify a chest without replacing it?
where can i find documentation for world dynamic properties
also is worldinitialise depriciated?
do you mean a container of a chest?
question is there a event that checks if someone takes a item from the gound (pickup a item)
or replacement
try using it
if (valid) {
// your code
}
thx dude
👍
Is it possible to get block broken % or smth?
Like how much is it broken
AND also when a player stopped mining it
try item events
There's also this new event in 2.1.0-beta: https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/playerinventoryitemchangeaftereventsignal?view=minecraft-bedrock-experimental
It should be in the latest update (1.21.90); I believe it's coming to stable in the next update (1.21.100).
thx
2.0.0 is out ??
Yes.
hell yeah
anyone know why doing this:
const entity = world.overworld.spawnEntity('f8:raycast', location);
entity.setProperty('f8:active', true);
does not set the property to the entity? It sets correctly if I dimension.getEntities() and set it in there, but not with the Entity class off the dimension.spawnEntity
How are you verifying it?
world.overworld.getEntities({ type: 'f8:raycast' }).forEach(ent => {
console.warn(ent.getProperty('f8:active'))
})
just spamming false in console
if I set it in the forEach it updates as expected
Setproperty takes 1 tick to apply.
I've never had this issue, I setproperty and it applies. Verified via client sync.
For console.warn I usually waitTicks(1) then verify.
I'm setting the property in a separate function altogether, it has nothing to do with it applying the property change next tick
The forEach console log is only to verify the properties and is being ran in a runInterval
Ah I see, I assumed the two code were being ran in succession.
system.runInterval(() => {
world.overworld.getEntities({ type: 'f8:raycast' }).forEach(ent => {
console.warn(ent.getProperty('f8:active'))
})
})
const entity = world.overworld.spawnEntity('f8:raycast', { x: -5994.5, y: 64, z: -5998.5 });
system.runTimeout(() => {
entity.setProperty('f8:active', true);
}, 1);
Pretty much just this
And it's just
I tried system.waitTicks as well, it did not change
Was this an issue in previous versions?
Maybe your minecraft:entity_spawned event is setting the property to false?
Don't even have that event in the entity code
Maybe another interval is setting it?
I would defer in acquiring the entity using EntityLoadAfterEvent.
was the .isOp method removed in 2.1.0-beta? It was working in 2.0.0-beta
@valid ice May this be something you can adapt?
export function onEntityLoad(id, callback) {
const handler = world.afterEvents.entityLoad.subscribe(function cb(arg) {
if (!arg.entity.typeId != id) return;
callback(entity);
world.afterEvents.entityLoad.unsubscribe(handler);
});
}
world.overworld.spawnEntity('f8:raycast', { x: -5994.5, y: 64, z: -5998.5 });
onEntityLoad('f8:raycast', (entity) => {
entity.setProperty('f8:active', true);
});
Want to unsubscribe from it after, of course
EntityLoad has never worked properly for me. I would use EntitySpawn.
There’s definitely workarounds I can do to get it functioning, I’m just unsure of why it refuses to set in the first place
Perhaps just a flaw. Or a quirk with properties specifically.
Yes, use
player.playerPermissionLevel
Go with the silly workaround for now, then report that as a bug to whomever/wherever it is most appropriate to
I think that one only works when the entity was in an unloaded chunk
Could be that I'm used to using EntityLoad with structures. I have not tried such a system with Dimension.spawnEntity
iirc it works in both cases
Nope, doesn't work as well.
thanks
Seems to work OK for me with structures. I use structures to spawn AOE clouds, then use the technique I mentioned to get a reference to the summoned entity.
https://github.com/Bedrock-OSS/bedrock-wiki/pull/1057
for some reason i cant get an entities location when i use player.getEntitiesFromViewDirection
can anyone help me with this?
/something/ is a regular expression literal. It is almost the same as using the global RegExp() to make one.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
NOTE: Some things on that site will not work due to being removed for security reasons, or they don't apply / were not added.
https://regex101.com/
This site helps with testing if a Regular Expression pattern is valid. You can also use it to help with testing that it is working as intended.
NOTE: Remember to select the "ECMAScript (JavaScript)" flavor before you start. (Also note that some stuff might not work with the Scripting API).
Awesome, thank you for your reply, I’ll look into all this when I have time to code again.
If it will never change, use the literal syntax.
This is a naming system using modal not a custom command, I think that’s what you mean right? I’m still very inexperienced I only started with script a few months back so hopefully I understand you correctly.
just like how 123 is a number literal and "omg" is a string literal...
Oh ok, I think I got you correctly. Rather than sending through a filter like [^0-9]?
Gotcha, but those are opposite right? The regular expression pattern is the opposite of a literal string?
mssg.match([^0-9])
[^0-9] is invalid JavaScript.
Oh uh, 🤔 I think I need to learn more lingo to have this conversation haha.
A regular expression pattern must be surrouneded by / characters:
/[^0-9]/ // that is a regular expression literal.
'foo' // that is a string literal
"bar" // this is also a string literal
// This creates a variable named `first_name` and
// points it to the area in memory holding the string
// with the value of `Billy`
let first_name = 'Billy';
// Similar but instead points to the area in memory
// holding the object instance for the regular
// expression (with the pattern shown inside it).
let pattern = /^[0-9a-zA-Z]+$/;
// Both of the following two lines are the same.
result = first_name.match(pattern);
result = pattern.exec(first_name);
whats popin
Not much
@chrome gyro (see what I am "replying" to here... I forgot to ping you in it).
Got it, oh wow, ok thank you for putting that together. Sorry at work, I don’t have a lot of free time to read just a few minutes here and there.
This only tests if the pattern was found or not. Use if it you are not going to take specific parts out of the string that the regular expression matched against.
REGULAR_EXPRESSION.test(STRING)
These always create a new Array if it succeeded.
STRING.match(REGULAR_EXPRESSION)
REGULAR_EXPRESSION.exec(STRING)
^ In case you already turned your phone off.
Ok I think I get it now. It’s only a test for failure, so I’m probably better off using the .test() that way it doesn’t create a new array right?
Does it delete the array after the exec / match?
Yes, but it may take a moment for the JavaScript engine to actually remove it from memory.
Ok, awesome. so it does cost more, and shouldn’t be used in a repeated every tick or something, but for a one time test probably is ok. Thank you for your detailed responses!!
Using a regular expression object's test method is more ideal if you only want to test if it matches some criteria.
But why test every tick?
I don't think you should be testing it every tick unless you are trying to debug why something is broken.
Guys
If you have a question, just ask the question.
Uhm I know it's literally "Coddy"
Anyways, is the face location bugged?
Are you expecting it to be somewhere it isn't?
What happened to your old account?
I just mean hypothetically you wouldn’t ever want to do that since it would be so costy.
2FA? ....
Whaaat? Hmm.
Multi factor authentication...
wait I'll send later after eating or if I found codes... Fvk
The more common term is Two-Factor Authentication or 2FA for short.
Okie but idc lmao
Mainly was directed towards those who didn't understand what you meant
😢 thats probably really bad, sorry.
It is, especially if your email is locked behind it as well.
is this what are you referring to?
yes but it some location of the block it works but when place in some it's broken asf.
You can't tell me my script is broken if my script is literally small asf
And I rarely make broken script 😭
Assuming you are using the player's face, have you tried to add the value to the player's coordinates?
import { world, system } from '@minecraft/server';
world.beforeEvents.playerInteractWithBlock.subscribe((ev, { block, blockFace, faceLocation } = ev) => {
if (blockFace !== 'Up' || block.typeId !== 'minecraft:furnace') return;
ev.cancel = true;
const dir = block.permutation.getState('minecraft:cardinal_direction');
let { x: fx, z: fz } = faceLocation;
if (dir === 'east') [fx, fz] = [1 - fz, fx];
else if (dir === 'south') [fx, fz] = [1 - fx, 1 - fx]
else if (dir === 'west') [fx, fz] = [fz, 1 - fx];
// else {}
const cell = `${String.fromCharCode(65 + Math.floor(fx * 8))}${Math.floor(fz * 8) + 1}`;
console.error(cell);
});```
maybe share your code and the problem you are facing
I'm trying to send a vid if my discord isn't ass rn
Either too large of a file, or it is taking a while to scan
Are you using 2.0.0?
yep, 2.2.0-beta
Here....
Like wtf?
Why are you not also outputting the coordinates in your "error"s you are making?
and you think I didn't do that?
Wait I'll be dealing with my 2fa
You were only showing a letter and number... nothing else
weird
why is that not the same in all locations
not shown yes not doing it no.
can we remove the namespace of the custom command now?
you can use them and if they are unique, they appear without a namespace
shouldn't this be different? or is it local based but not based on the block origin
actually no, @jagged gazelle there is your answer
it is not based on the block origin
the video you sent is of blocks in different zones +x +z and -x -z
and that is why they are different
Ohhh damn.
Okk I didn't fully understand the docs, my reading comprehension is bad
thanks man. I'll try that later after finishing this 2fa
this is basically what you are doing with the 1 - xy
you can see how it is wrong in the -axes
np
its heavy
generally regex its heavy as hell
its not good for performance stuff
and nobody understands this shit
I love regex, I spend a whole 2 months understanding them
Bonus? I lost my mind. I hate it.
its preferred to simply avoid them
i understand bro
when i see some code right regex i simply skip that part
depend, not going to use it for a simple check
but depending on your way of handling complex tests, it can be way faster
i dont know what a regex engine does under the hood but probably is some kind of tokenization
Especially texts.
They are so handy.
true
i would use includes and startsWith and other simple stuff when i can, but stick to using regex for complex matching patterns
great to have you back haha
hope things stay that way for you, i mean shit happen but that is life for you
im getting the habit to check stuff by using charCodeAt,
if theyre single char for sure
normally i prefer writing tokenizers when talking about more complex pattern
but usually the patterns i tend to make arent human readable
so regex is not an option
yeah, it depend on you use case, string[index] work too
it's more readable but if you see some optimization tricks on v8, comparing by string normally is not a good idea for performance
haven't tested out the performance of those so i can't really tell
i will take your word for it lol
i think i still got something on my browser history
charAt and charCodeAt
any different?
i think charPointAt
something like that
charCodeAt gets the u16 value of the character
Katie mentioned that too. It should be ok for my purposes. It will only be for a little bit that coincides with closing a ui. I’ll just use the better method going forward.
i assume charCodeAt return a unicode?
you mean the number?
if so yeah
it gets the underlying number for that character in utf16
alright
always been.
bloating in searching too
coddy2? why 2
Lost my main acc because of 2fa shyt
also does anybody know the link for the new startup event changelog that will be kind of replacing worldLoad?
oh dang that's why you didn't reply to my dm 😕
Oof
Thanks a lot smokey
@wary edge @sharp elbow Apparently the issue was the delay in the function.. doing spawnEntity and then setProperty in the same tick does set the property, but delaying setProperty does not set it. I tried recreating it in a bugtest pack, but it worked... seems like something weird with my codebase.
Hi, my command fails to detect that when the targetcamps is at 1 or 2 it displays its camp
if(msg.startsWith("!scanner")) {
if (!player.hasTag("oracle")) return player.sendMessage("§cVous n'avez pas accès a cette commande !");
var arg = msg.slice(9).trim().toLowerCase();
if (!arg) return player.sendMessage("§cUtilisation: !scanner @pseudo");
if (arg.startsWith("@")) {
arg = arg.slice(1);
}
// Vérifier le cooldown
const cooldownScore = f.getScore("cooldown", `${player}`, true);
if (cooldownScore > 0) return player.sendMessage("§cVous devez attendre avant de réutiliser ce pouvoir !");
// Trouver le joueur ciblé
const targetPlayer = world.getAllPlayers().find(p => p.name.toLowerCase() === arg.toLowerCase());
if (!targetPlayer) return player.sendMessage(`§cJoueur "${arg}" introuvable ou hors ligne !`);
// Récupérer le camp du joueur ciblé (pas du scanner)
const targetCamps = f.getScore("camps", `${targetPlayer}`, true);
// Ajouter le tag scanner
player.runCommand(`tag "${player.name}" add scanner`);
// Déterminer le message selon le camp
let campMessage = "";
if (targetCamps == 1 || targetCamps == 3) {
campMessage = "§qGentil§e";
} else if (targetCamps == 2) {
campMessage = "§4Méchant§e";
} else {
campMessage = "§7Inconnu§e";
}
// Envoyer le résultat
player.sendMessage(`§eVous venez de scanner ${targetPlayer.name} et il est ${campMessage}. Désormais vous pourriez le scanner à nouveau dans 2 Jours`);
// Appliquer le cooldown et retirer le tag
player.runCommand(`scoreboard players set @s cooldown 2`);
player.runCommand(`tag "${player.name}" remove scanner`);
}```
could someone help me please
what is "f", and the getScore() takes the player first, not the objective
If "f" is the score objective, you need the player/entity as the first parameter, as the objective is built into the "f"
gotcha
Swap your objective & player, in that case
const targetCamps = f.getScore(targetPlayer, "camps", true);
Assuming that you are importing as f
@random ibex ask in here
thanks
Can someone help me make a script so that a player cannot exit the game during a battle?
Is that even possible
you can punish the player upon logging back in
or, something more advanced that I did recently, was spawn an unmoving gametest bot in their place and copy over their player data, so if they log out the bot has to be consciously killed
what's a gametest?
@minecraft/server-gametest module; lets you run unit tests on certain game mechanics. Not terribly useful, but the simulated players in the module are a carbon copy of actual players in-game and let you play with and set their AI.
That is pretty clever
It also removes the simulated player after 10 seconds, so if they have not been killed by then they've successfully "logged out" regardless of where they are or what their health was at the time (hitting them resets the timer)
that's interesting, ima look into it, thanks for the info.
what about structure
hello again people I need some suggestion on how to do this:
OnTick:
function sspawn entity after 5 seconds
function spawn entity after 2 seconds
however there is a conflict with the timer variable im using, what's one way to make a unique timer for each?
Use a map and store each timer separately via a manager class or something
manager class?
Yeah. Like a timer manager class
tick every second, run something every 2nd tick, run something else every 5th tick
in-code counter to store current ticker
You could also just use system.runInterval() with the delay
Or have two ontick custom components
Not even that, system.currentTick % 2
Theres multiple ways to handke thism
darn. thought we had localization strings available for custom command description and parameter names
guys
how to detect player place block
i am using place block and interact block event, but i cant figure it out to detect if player is placing block and not interacting block
before event btw
prioritize placing block over interacting
finnafinest
const entityLoc = player.getEntitiesFromViewDirection()[0]?.entity.location
what
help
yes
Math.random()```
what
how to fix
and
put in manifest
ok.
it wont work
your first bet is:
learn scripting first
i did
the fuck you want by putting math.random() inside the whole script and that's it
bc
nah it's just kind of joke bye
no
i asked chatgpt
it said put in main.js
for rng system
pls
what
wat do you even want to make
Send your current code, what you are trying to do, and why it doesn't work
bro just put math.random() in whole script and calls it a script
it not whole script
what
Saying a native JS mathod doesn't work is extremely bad debugging and does not tell us anything about what code you are writing
dude do you think saying that 'math.random' is your problem can help us identifing the problem??
Tell me your error
and full code
So to answer properly: what exactly do you mean by "fix"?
💔
hero do you watch jojo
no
it's good watch it
Dude is at it again?

what
-# who are you referring to
bro you're targeting me
stop
i asked for help and you told me to learn it myself
system.runInterval(() => {
const dimensions = ["overworld", "nether", "the_end"];
dimensions.forEach((dimension) => {
const entity = world.getDimension(dimension).getEntities({ families: ["cnb_entity"], })
if (!entity) return;
entity.forEach(entitys => {
if (entitys.dimension.getBlock(entitys.location) == undefined) return;
Would it help lag if I somehow got the dimension of any loaded entity then ran the thing? Is this actually executing the whole thing three times?
thank you, why does it work differently with getBlockFromViewDirection()
Yes. You should actually cache each dimension on startup though
const targetedBlock = player.getBlockFromViewDirection()[0]?.block```
me when extend native properties
const formatTime = (milliseconds) => ({
days: Math.floor(milliseconds / (1000 * 60 * 60 * 24)),
hours: Math.floor((milliseconds / (1000 * 60 * 60)) % 24),
minutes: Math.floor((milliseconds / (1000 * 60)) % 60),
seconds: Math.floor((milliseconds / 1000) % 60),
});
fix?
super easy, barely an inconvenience
I could see that, does it really cost that much though?
The trick lies in the .d.ts file, because js does not give one iota about what you're changing
-# typescript, on the other hand...
You could try profiling it. E.g. start a timer, execute the function once then print the time it took
I'll have to look into doing that, good idea, it would be helpful to know for optimizing. Still a bit new though, so it might be a little bit. Thanks!
You can do
const start = Date.now();
RunFunction();
console.warn(Date.now() - start);
@vast grove please block me
No. I'll just use the ignore button
Really, it would be that simple? It would show a time distortion somehow.
ok i'll block you
Interesting.
Yeah. It'll show in ms
The difference
Too many 60s
wdym it works
function addItems(player, items) {
system.run(() => {
try {
const inv = player.getComponent("inventory").container;
for (let [item, count, enchants] of items) {
const itemStack = new ItemStack(item, count);
if (enchants && enchants.length > 0) {
const enchantComp = itemStack.getComponent(
"minecraft:enchantments"
).enchantments;
for (const enchant of enchants)
enchantComp.addEnchantment(enchant);
itemStack.getComponent("minecraft:enchantments").enchantments =
enchantComp;
}
inv.addItem(itemStack);
}
} catch (error) {
console.log("inventory", error);
}
});
}```
Ooooh cool, thanks!
@chrome gyro
Example of some extensions:
I looked it up. Looks fairly simple but a bit more effort than what I am used to :/
Adds a few things to Entity class, and by extension Player class, as well as adds some stuff to native js modules
😂 I say this, but I just went back and looked and I have it in 15 different places lol.
Me when micro-optimizations but they're for MC modules 
Is there a way to do a memory dump once the load gets to be too much? I'm probably not saying that correctly, hopefully that makes sense.
huh
JS is scripted and there's no real manual memory alloc like low level lanuages so really the only way to dump memory is to basically dereference stuff.
Aw man, ok. thanks again.
One way to improve memory management is to reuse stuff like object pooling
Or even caching
And then reducing API calls is another mc specific optimisation
That's a good idea, I think I've done as much of that as I could though. I've consolidated a lot of variables... not sure I can get that down anymore... I think I added too many variable haha.
what's an API call?
If you're using a server, I'd recommend a daily restart to clean up unfound script garbage
Even if not BDS, it's good practice to perform a daily restart
Something like world.getDimension(); is an api call. Something like Date.now() is not an api call since it's native java
So any function you call that is part of the MC types is an api call, some of the properties/members are api calls too for some reason...
Interesting I didn't know that was possible. This is an addon I"m working on, unfortunately it's entity based so I'm trying to optimize that as much as possible.
Oooh ok, something that grabs a variable from Mojang?
Eeehhh yeah most things are an api call. Some aren't cuz they are constants iirc.
This. Almost all (all of?) the script API calls are extremely slow compared to native JS methods, so caching data is generally a better choice
That
Ooooh that that.
Native JS calls are extremely efficient, being a language that has been worked on for many many years, so micro-optimizations in that area easily pale in comparison to those in script API
I used scoreboards to store a lot of the variables, I think the issue is calling them back to do the thing.
Native JS calls, ok I'll have to look into the differences between them then.
Apparently Entity.position is an api call 
Idk. Inconsistencies. Should make it so any api call is a function, not a property or member
One thing I do for scoreboards, where I use them, is:
const objDB = {};
setScore:
const scoreObj = objDB[objective] ??= world.scoreboard.getObjective(objective);
getScore:
(objDB[objective] ??= world.scoreboard.getObjective(objective))?.getScore(this) ?? 0;
TLDR just caching the ScoreboardObjective class used to retrieve values
Mfw .isValid() -> .isValid
Yes! I've relied heavily on that method for this addon, I threw it into a function though so I can get the common 15 scores that I keep needing to grab.
Speedy!
A what now?
better than retrieving score every time
They made isValid for blocks, items, entities, dimension, location, etc. a property rather than method
Bruuuuhhhh

Yeah, plus if I do an update, I only have to change it in one place.
What the hell is going on...
With the api
Or the team
What standard are they following
And yet here we are complaining on Discord, the best coded website of all time™

I love modern ~~web ~~dev
Makes sense. I was thinking more of coffee with 10x caffeine
Basically this stuff.
Each entity rn has a 5 ms delay when ran at full speed which is every tick. Is that bad? Every time I add an entity it ups by 5 ms. After about 20 it starts to make things like throwing items slow significantly.
Oh yeah that's not great...
Hmmm I'm tempted to add a cap on ticks. so players can only make the speed down to like 10 ticks.
Anyway, thanks for the input and insight... I'll come up with something.
Hmmm.. nope haha the delay is the same no matter the ticks. I think the load is too big.
You could try using jobs. But idk if that's a good solution since I've never used them. Look at what part is the biggest slow down and try to find solutions
Like is it the getting blocks part?
Or getting the entities part?
If it's the getting entities part, try looking at caching them
Like, if multiple of the same entity, then only running once for that same type kind of thing?
I meant like listening to entity spawned, loaded and destroyed events, add them to an array and loop over that
Instead of doing a double loop
It's event based which will improve perf a fuck ton
You're essentially skipping 2 API calls
Per tick
Oooh interesting, ok I'll try that tomorrow.
Jobs are good whne you don't care about timing
Really, really good
But
The other code, you'll have to figure out how you're gonna improve. Like reducing the amount of variables you're getting from the API into something smaller or even just storing less things and possibly even moving some to function commands.
I thought about compiling more variables into a single scoreboard name then just slicing. Idk if I'm up for that just yet though, I'm kind of sick of scoreboards after this XD.
Is there a reason to use scoreboards? Otherwise you could use dynamic properties
I think they run faster??? Idk, also I haven't learned dynamic properties yet, I keep seeing them when I search, but haven't figured out exactly what they are.
Or is it the same as properties in an entity?
They're essentially like variables you can store on the entity or world. They are individual to each add-on and they're persistent
Plus you can store a lot in them
Very useful, fairly optimised
Strings, bools, numbers, even vectors
Better, as they’re dynamic ✨
Entity.setDynamicProperty(identifier: string, value?: boolean | number | string | Vector3): void
Very easy to use. Easier than scoreboards
what the whaaaaat? I just found out this was in my code for the function:
for (let i = 0; i < 1; i++) {
}
I think I was too inexperienced at the time when I added that part to know what it did.
Oh wait... maybe it wouldn't have mattered?
Entity properties are fantastic when communicating between regular BP & RP files, but have limited use when it comes to set-able values (have to define beforehand)
Dynamic properties are solely scripts, and can really set whatever values you want (JSON.stringify() & JSON.parse() OP) with the limitation of being only script based
Oh! Wait a minute... is this a dynamic property?:
grouping.setFloat("variable.cnb_ppl_ptime", time )
That’s a molang map, probably a particle, If I had to guess
Also limited, sadly, as you have to “infer” the type of variable using regular json beforehand
Ok, hmm maybe I need to try out some dynamic properties then and see if applying them helps... Thank you both so much! I have a lot I can try now.
Still a great tool for script to particle translations!
The big thing is that dynamic properties are solely BP side with zero RP interactions, so
Oooh I was just going to ask that. Ok I gotcha.
... Weird shit.
Whaaaaaaat!!?!?!? I dont understand. Ok, so I made the function grab the scores directly using this method... instead of going to the other function where it unpacks the scores.
With 15 entities down I was getting 45-70 ms delay, after changing it to just grabbing the scores directly it went down to 5-10 ms delay now 😄

Sorry, that probably didn't make any sense I can type it out.
Caching helps a lot, but be wary of how much caching— it does make a difference.
You’re definitely fine for score caching, don’t worry
That's a fair warning... I think whatever addon I make next I will make sure it doesn't have so many variables by design.
Performance is the main concern when it comes to bedrock scripts
Wouldn't be so damn important if they used C# instead

I'm still annoyed they weren't able to use it
I'm starting to realize that 😭
I want the operator status of the player to fluctuate depending on the quantum state of the qubit I’m referencing
At least with C# you're not completely free to do everything but it's still very good since it's optimized at compile time. Roslyn analyzers go brr
Oh fuck. Source generation!
Omg hahaha, only if not observed by another player though.
Does an "observer_block" count as an "observer"?
This is another language to me 😏
C# has it's own built-in array pool.
var encodeBuffer = ArrayPool<byte>.Shared.Rent(Constants.MaximumEncodedBytes);
So much stuff that JS just doesn't have
what does that do?
Js is bad but of course humanity adapted it for the general internet
Gets an already allocated byte array of that size if it exists, otherwise it'll allocate a new one and return it. Less allocation, more reusing.
It's like a set of glass cups, why use a new one when you can just wash and reuse the same one?
Why do that when you can just order new cups every time you need more
Oh gosh
Sure, it costs more, but think of the convenience!
Garbage man won't like you
oh that's handy and much more performant
I had the chance to learn C# with rimworld but it was too difficult to me
Welp. My day is wasted. I was gonna work on something then I didn't. Now I just wanna play a game.
HELP
dude, You're my d1 hater
Ok. So ask questions properly then I'll stop being a dick to you
"✅ Be Respectful
Be kind to others. The people on this server are of all ages, nationalities, races, and religions. Slurs, targeted vulgarities, and advocations of self-harm are not allowed."
if (player.location.y <= 319 && player.location.y >= -64 && player.dimension.id === "minecraft:overworld") {
const blockFeet = player.dimension.getBlock(player.location);
const headLocation = { x: player.location.x, y: player.location.y + 1.0, z: player.location.z };
const blockHead = player.dimension.getBlock(headLocation);
if (blockFeet?.isValid() === true && blockHead?.isValid() === true) {
const lightLevelFeet = await queryLightLevel(player.dimension, player.location);
objLightFeet.setScore(player, lightLevelFeet);
const lightLevelHead = await queryLightLevel(player.dimension, blockHead);
objLightHead.setScore(player, lightLevelHead);
}
}
if (player.location.y <= 127 && player.location.y >= 0 && player.dimension.id === "minecraft:nether") {
const blockFeet = player.dimension.getBlock(player.location);
const headLocation = { x: player.location.x, y: player.location.y + 1.0, z: player.location.z };
const blockHead = player.dimension.getBlock(headLocation);
if (blockFeet?.isValid() === true && blockHead?.isValid() === true) {
const lightLevelFeet = await queryLightLevel(player.dimension, player.location);
objLightFeet.setScore(player, lightLevelFeet);
const lightLevelHead = await queryLightLevel(player.dimension, blockHead);
objLightHead.setScore(player, lightLevelHead);
}
}
if (player.location.y <= 255 && player.location.y >= 0 && player.dimension.id === "minecraft:the_end") {
const blockFeet = player.dimension.getBlock(player.location);
const headLocation = { x: player.location.x, y: player.location.y + 1.0, z: player.location.z };
const blockHead = player.dimension.getBlock(headLocation);
if (blockFeet?.isValid() === true && blockHead?.isValid() === true) {
const lightLevelFeet = await queryLightLevel(player.dimension, player.location);
objLightFeet.setScore(player, lightLevelFeet);
const lightLevelHead = await queryLightLevel(player.dimension, blockHead);
objLightHead.setScore(player, lightLevelHead);
}
}
}
});```
Getting an error on line 10
Again. not descriptive enough
oooohhhh riiiggghhhttt. and what's this?
pretty sure this is quick questions for a reason
is it possible to modify the players health componenet and add a minimum value to it then modify it again and remove it?
No it isn't. You posted an entire code block, no context, you didn't show the error. I cannot be bothered testing it.
through scripts ofcourse not using player.json
I literally said there was an error on a certain line
Ok. So what is the error?
Instead of just saying There's an error on line 10 This does not help. It's like saying My power doesn't work
Dont you think i would be able to fix it if i knew
Buddy. You know there is an error on line 10. Show the error
otherwise I am going to just stop
And this shit is why I'll say bye bye!
Being a dick to me because i didnt say "help" the right was shitty.
And you not even telling me either is crazy
Oh sorry. did you say something?
you can only modify the current value
did your console say error on line 10?
what is the full error?
is the number 10 relative to the complete script or the one you sent?
const healthComp = deadEntity.getComponent(EntityComponentTypes.Health);
if (healthComp && healthComp.currentValue <= 0) {
healthComp.effectiveMin;
}``` what does this do the effectiveMin?
the script you send does nothing
effectiveMin return the min of the health
that property is readonly
world.afterEvents.dataDrivenEntityTrigger.subscribe((ev) => {
let lightLevel:
ev.getModifiers().forEach((d) => {
d.addedComponentGroups.forEach((compGroup) => {
if (compGroup.startsWith("light_level:")) {
lightLevel = parseInt(compGroup.replace("light_level:", ""));
}
});
});
ev.entity.remove():
promiseMap.get(ev.entity)?.(lightLevel);
}, { entityTypes: ["detect:light_level"] });```
saying there is an error?
anyway to make a death prevention method?
no
again, what is the error
what's the fastest way to visually debug a position (like a line or just a block)
particles or entities?
console.warn ?
or are there other methods
how do i check?
sorry forgot to type "visually"
hover over it
did u put : instead of ; twice
let lightLevel:
you meant
let lightLevel;
whats the current stable scripting version ?
2.0.0
2.0.0
hey im tryna use the search on jayly's docs and searched entity however it doesn't show the entity class
broken?
i tried to change from 1.1.0 to 2.0.0 and all of my forms shows error , is there any docs on new syntax ?
search for know entity functions or properties
the search is not broken but it is not the best
I see thanks
ex
just read the errors, they are self explanatory
how do i get rid of this blocked message thingy
error in the arg[0], expected type x
look for x in the docs
if you are on browser use ublock origin filters
It works fine for me I think. Did you get similar results?
thank you
nope
discord.com##.messageListItem__5126c:has-text(/Ignored message/)
Interesting that you don't have a scrollbar. What browser are you using?
OperaGX
might be uBlock?
nope
i don't have it either
send me that website rq
TypeError: Native optional type conversion failed. Function argument [1] expected type: ModalFormDataToggleOptions | undefined
this is the error , it doesnt say what argument it needs ?previously it was just boolean for default value in a toggle
As the Script API is a framework built on JavaScript code, having an understanding of JavaScript is key.
If you are being shown this, then you most likely are a beginner with JS and could use a little guidance.
Videos on Learning JavaScript
Javascript in 1 hour
Javascript Classes in 1 hour
Web Guide:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide
Reference Sites:
https://www.w3schools.com/jsref/default.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
https://javascript.info
oh wait
you have error in the second argument in that
search for ModalFormDataToggleOptions, some things changed
interface ModalFormDataToggleOptions {
defaultValue?: boolean;
tooltip?: string | RawMessage;
}
how to check player game version?
here u go
you can't
... I know tho
it's just I can't see it in the search bar
Can you check if this file is loaded?
that shouldnt really matter
that's not the issue here
It's not possible for it not be loaded.
nvvm, i am getting it
my search didn't have that many options
might've just have been an issue with the browser your using
refreshing the page might work, I just used a very hacky way to make the scrollbar (since typedoc doesn't officially support this)
It wouldnt really be hacking. Unless you're actually messing with the website.
...
anyways thanks for the website jayly I'll just refresh it if it happens again
where do i find this more about this , i have other form elements to update
i previously learnt from bedrock dev which isnt updated yet?
as i said, when it says it expect a type, just search for it
which site is that ? where should i search on
wierd how onPlayerBreak in custom components is lacking docs in the types
jayly's
any docs will do
types?
import { world } from '@minecraft/server';
world.beforeEvents.playerInteractWithBlock.subscribe((ev, { block, blockFace, faceLocation } = ev) => {
if (blockFace !== 'Up' || block.typeId !== 'minecraft:furnace') return;
ev.cancel = true;
const dir = block.permutation.getState('minecraft:cardinal_direction');
let { x: fx, z: fz } = faceLocation;
const { x, z } = block.location;
if (x >= 0) fx = 1 - fx;
if (z < 0) fz = 1 - fz;
if (dir === 'east') [fx, fz] = [1 - fz, fx];
else if (dir === 'south') [fx, fz] = [1 - fx, 1 - fz];
else if (dir === 'west') [fx, fz] = [fz, 1 - fx];
const cell = `${String.fromCharCode(65 + Math.floor(fx * 8))}${Math.floor(fz * 8) + 1}`;
console.error(cell);
});```
-# fixed
the ts type definitions
ohhh
I like how it took me 20 mins to find a solution for ts.js if (x >= 0) fx = 1 - fx; if (z < 0) fz = 1 - fz;
do u have a link to this ? i cant find it at all
Modal*
oh im stupid mb
Hmm, any like guidance for them?
ts (typescript)?
ts = this shit
Oh, I wonder how long until every word has its own abbreviation.
'-'
nah it's that shit
it is this, the error is in the code he sent
Say you have an entity at (0, 0, 0). You grab the location, it returns a vector of {x: 0.5, y: 0, z: 0.5}. Then you teleport that entity to (1, 0, 0). If you acquire the location again, should it be the same as before, or should it now return {x: 1.5, y: 0, z: 0.5}?
I like to think that most properties (if not every property) is a lookup call on the API
Read further.
I did, and I do not suppose I missed anything.
The message right after. I said api calls should be functions. not properties/members
I understand your point
It's just. It's a goddamn variable.
Then all Mojang need do is remove location and rename it to a method of getLocation. Now it behaves like you think :)
I like to make a copy of the entity's location so I only do one lookup. Then when I need to read from the location again, I have it cached.
const location = {...entity.location}
Yeah I know that...
If I need to manipulate the location, I can edit that vector as many times as I please. Then I can set it at the end
My scripting style heavily uses variables as a result. The code on my current project would probably make some people here cry
Syntactically. having it be a property/member doesn't explicitly state it's something that's available to get without having to make some conversion api calls. Kinda like a web server, would you hide a get request behind a property? It just doesn't make sense...
That's why I am not a big fan of setters and getters
You don't know from an outside interface if that property lookup is doing something more sophisticated behind the scenes.
And I guess, in essence, most properties in scripting are getters? Perhaps not literally
exactly. Even the docs don't tell you it's an API call and being as it may with performance being a big concern with script api. These should be defined either in syntax or by a note.
I can also see a point where including that might be TMI. Generally performance should not be too big of a concern to the lay user
I would like an article from the team describing some optimization strategies—real ones at that
Or if it does not already exist, how to profile a pack and determine which calls are consuming the most amount of time
Yeah. That would definitely help a lot of new scripters understanding why their code is so slow.
A colleague of mine wrote some not-so-optimized code a few weeks back that made me want to cry when I read it
General utility functions are great when reusing across the pack, but such self-contained functionality really needs a cache if you are going to make repeated calls with very similar data 😢
I guess this is why wrappers exist? To help alleviate some of those manual caching calls?
I suppose so. A good wrapper would do that, I would think
I kinda hate how getHeadLocation(); is a function and shows it does something to get something
Same with getRotation. But at least it's clear that it's a method!
Replace isValid with getValidity()
It was apparently changed from a function to property...
that just sounds stupid
the word get its just bad
get is a meaning of getting something but I understand your point in this case.
That's true, I forgot lol
get sounds more like for Map dynamicProperties usage
I wonder if Entity.id is an api call. I doubt it is but if it is. Goddamn I would be surprised.
Only one way to find out!
why am i unable to detect the food itemStack saturation?
Get this component on the ItemStack
https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/itemfoodcomponent?view=minecraft-bedrock-experimental
const foodSaturationValue = player.getComponent('minecraft:equippable')?.getEquipment('Mainhand')?.getComponent('minecraft:food')?.saturationModifier;
yup
returns undefined
yes, it is undefined for some reason
what item are you testing it on?
steak
Ok yeah that's weird...
the food component is undefined
like
console.warn(itemStack?.getComponent('minecraft:food')) returns undefined
When present on an item, this item is consumable by entities. Note that this component only applies to data-driven items.?
But I thought food items were data driven... according to the bp on the mojang samples...
wtf
console.warn(itemStack?.getComponent('minecraft:food'))
minecraft foods except the apple dont have the food component
They're holding a cooked beef.
Original getCamoState average time: 0.051711560000000205 ms
Optimized getCamoState average time: 0.00015244999999937362 ms
Each ran 10k times
goddamn
I shoulda been using hashmaps a long time ago
That is actually insane how fast it is compared to what I was doing
339x performance improvement
omg, now my script runs at under 1ms 😭
It used to be 20ms when it had to search through a giant map, but now with the optimisations I made, it runs under 1ms to get to the same block check 😭
how do you check that
debugger extension in vscode
ooh
It's actually amazing and has made me look through my code due to how shitty it was running
i noticed this too
it just straight up doesnt work
how does it work?
not at my pc rn
so can't download it
at least will it works for modded items? not the vanilla ones
not sure
considering that vanilla food items are data driven, it probably doesnt work for addon items either
I'll try it anyway
i think this is related with eatItem method not working even with valid food ItemStacks
Try this
system.run(()=>{
console.warn(itemStack?.getComponent('minecraft:food').typeId)
})```
wait, what
Even with typeId it's still undefined?
TypeError: cannot read property 'typeId' of undefined at <anonymous> (./development_behavior_packs/main.js:8) (main.js:8)
system run make no sense there
it works for custom items, but not for the vanilla ones
I was getting an error of wrong privileges, so I had to put it in a system.run
odd
that is actually pretty good!!
[ReferenceError: Native constructor for [ItemStack] does not have required privileges. at ItemStack (native)
i can get the vanilla items saturation from the wiki
Ye
the food components isn't exposed that's why.
Bit weird to me that you can't get the saturation from vanilla
oh
and get the saturation of the other addons food using the script, so i can use it
food, compost etc. isn't accessible to a VANILLA item
Still a bit weird they aren't accessible on Vanilla items
while for custom ones they are exposed that's why they are accessible.
Smokey had explained this before.
it does.
(i am making AppleSkin for bedrock, so i need to show the saturation when u hold the food on ur hand)
lets do this!
okie, I'm still brute forcing my main acc
I hate 2fa, I forgot I have activated it before
See you in two gorillion years
before u guys even ask, i have the permission to do that.
Erm actually it's 2.8 trillion possibilities
What's AppleSkin?
it would take me 450 thousand years lmao
That changes every 30 seconds
okie sry also what hapen to your old account
Oh nice
i just need to show how much hunger / saturation u will regen by eating that specific food
Someone in dev resources already did that..
anyways, gotta add the vanilla foods to the system,
huh?
if vanilla items.
oh wait I thought grabbing the saturation
Mbmb
if (itemStack?.typeId === 'steak') {title stuff}
Why not change the language files
Ah was thinking of something else, nvm
i will add that anyway
Herobrine, what's the limit of dynamic properties string values again?
it was 32... something
function getFullData(target, name) {
let data = '';
for (let i = 0; ; i++) {
const part = target.getDynamicProperty(`${name}:data${i}`);
if (part === undefined || part === null) break;
data += part;
}
return data ? JSON.parse(data) : {};
}
function setFullData(target, name, data) {
const stringData = JSON.stringify(data);
const parts = Math.ceil(stringData.length / 32767);
for (let i = 0; i < parts; i++) target.setDynamicProperty(`${name}:data${i}`, stringData.slice(i * 32767, (i + 1) * 32767));
for (let i = parts; target.getDynamicProperty(`${name}:data${i}`) !== undefined; i++) target.setDynamicProperty(`${name}:data${i}`, null);
}```
-# Found it. Nvm
well, as for my AppleSkin script, i need to add the food nutrition value to the current hunger value of the player,
i can do that pretty easily using the food component, but that doesn't work for vanilla foods so i have to sort the vanilla nutrition value so i can add it to the player current hunger value to render the ui,
how can i do that?
like should i use dynamic properties or something?
i know, dynamic properties are the best and the easiest method, but i dont think if my loop can make it works correctly
if you want to grab value then display in screen, dynamic property alone ain't gonna work, make dp as your storage, display them using title, subtitle, actionbar, scoreboard or chat.
hold up nvm
i know about all of those, i just need to get the vanilla food nutrition and saturation, and i know how.
like should i use dynamic properties or something?
then wym by this?
i am getting the vanilla food nutrition and saturation from the wiki and apply them as dynamic properties for the player, so i can use that number and add it to the player hunger and saturation to show u how much hunger and saturation this food will restore
how do i check if an entity is touching an block?
touching...? 🤨
uh you mean so touching ground...?
player.isOnGround and for the walls you gotta teste the distance from the player to the wall and find the correct one to detect touch
i mean thats just ground tho
ye
hmm
thx
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]
I can't find custom compass point locations in the docs. Is it possible? I could just set world spawn but that feels like a bad solution
No.
lodestones or setting world spawn
I see, can the scripting API attach a compass to a lodestone?
I'm not sure if I'm looking in the right place but I'm reading through item components
Don’t think it can
Ouch, alrighty, thanks!
I know this is probably a dumb question but does the value of for loop stay after player leaves the world?
Entirely depends on how you set it up.
To edit player default health do I need to edit the player.json?
if decreasing hearts yes
But for increasing, you can use health boost effect too
Alrighty, thanks
Wow I managed to mess that up lol
Maybe not...
I guess no health for me
No, you can't set it as component.
apply it as component groups
Ah right, thanks
Does it have a specific group name?
you have to use component groups and assign them using events
Is this worthy in the script resource or not? Basically, ender chest scanner... stupidly fast
#1386244732794966117 message
I see, thanks
that lag spike is a big problem
The only lag spike you see there is my Minecraft having trouble to open the chat UI while I have my screen recorder on in the background
yo Im stuck with the applyKnockback,ik how to make it go to the front and back but idk how to make it go to the right and the left of the player
const viewDirection = entity.getViewDirection();
const horizontalForceL = {
x: viewDirection.x * 1,
z: viewDirection.z * 1
}
return entity.applyKnockback(horizontalForceL, viewDirection.y * 0)```
Can you view whats in a shulker using JS yet?
I heard about using droppers/placing it down, but not a fan. Just coming back to this, and seeing if any new developments been made on it.
isnt there storage_item component thingy now?
I heard about that
yah but maybe it won't work?
Why is there a Second coddy
Just check the desc of my acc lol
No.
i think theres workaround
btw Coddy [second], what happened to ur main account?
Can someone help me make a script?
u can check out my addons scripts, they might help u a bit
https://www.curseforge.com/members/tryagain/projects
I'm looking for a script that has a command that anyone can put in the chat and it will open a kind of tab to redeem a code and with that you will win something
formUi?
if u want to open a formUi with redeem code system, u can do that but sadly i dont have the codes on my uploaded projects
I don't know very well but I just know that you have to type a command with the game chat and it will open a box to enter a code and with that code I can redeem an item.
i see what r u talking about, custom commands are beta,
u can learn from here ig
https://youtu.be/QhJkCDIZ-NU?si=kmhKXb9Pl62ttuMr
In this video, I demonstrate how to use JSON UI in combination with the scripting api in the Minecraft Bedrock Edition
🔗Links :
Like What I Am Doing? Concider Supporting Me! : https://ko-fi.com/dingsel
Join my Discord! : https://discord.gg/tzrmH56JXC
My Website : http://skyls.de
Music : https://www.youtube.com/watch?v=tEzYsaLm7nw&ab_channel...
And how do I do it instead of clicking I had to type?
i literally said check my acc about me.
btw, how tf is he opening an inventory ui using commands?
https://youtu.be/wdo2tagU388?si=LSoJC7y_CXNw4r4d
What is up crafters? Today I showed you how to convert GUI for Minecraft Bedrock and GeyserMC. That's literally it, this is really simple and lots of people have been asking me for it, SO HERE YOU GO.
Sorry if this video wasn't as entertaining as usually; I had to record it in my conference room.
Converter: https://abishekbhusal.com/j2b_gui/
...
server client things or something?
I feel like that's not script only
like when he typed /rtp in the chat, he have opened an entity inventory somehow
third party software too
i checked out the gui he made (its just a chest screen), but im not sure how did he opened the chest ui using that /rtp command
like is it servers exclusive only or something
system.beforeEvents.startup.subscribe((int) => {
const CameraCommand = int.customCommandRegistry;
const options = ['add', 'reset' , 'remove' , 'list' , 'visit'];
const command = {
name: "easy:cam",
description: "allows to creat §eCinematic§7 shots with no headache",
permissionLevel: CommandPermissionLevel.Any,
optionalParameters: [{
name: "easy:enum", type: CustomCommandParamType.Enum
},
{
name: "name",
type: CustomCommandParamType.String,
optional: true,
}
],
};
CameraCommand.registerEnum("easy:enum" , options)
CameraCommand.registerCommand(command,CameraSystem);
});
function CameraSystem(origin , mode , name){
const source = origin.sourceEntity;
if(source.typeId !== "minecraft:player")
return source.sendMessage(`§c[ERROR]§f -No player detected`);
if(mode === undefined)
return source.sendMessage("help");
if(mode === 'add'){
console.log('working')
try{
const i = customFunctions.Counter(source);
console.log(i)
source.sendMessage(`${brand}${colors.impotant}Position ${i}${colors.neutral} was added ${colors.success}Successfuly`)
}
catch(err){
if(err instanceof systemErrors){
source.sendMessage(`${ErrPref}${err.message}`)
}
}
}```
The game doesn't detect the "mode"
a plugin probably
honestly it looks like a crossplay server
nevermind it is java and bedrock crossplay
Command args is an array of inputted things, not just a single value
So mode in your function is an array
yah that might be the answer.
does anyone have a GOOD scoreboard database I don't feel like making one
When it is optimal, use regular string splitting / etc.
When it is used a lot less, regular expressions might be okay (it depends on what your pattern is).
But when it comes to parsing HTML and such, sometimes you should just use the right tool for the job as explained in this answer: https://stackoverflow.com/a/1732454
Is this a question?
Just a tip... and for a conversation that is around yesterday my time. Apologizes.
as I said, third party software... just scripts alone isn't possible it's limited rn and y'know that.
there is no packet to open a gui?
Probably there is I dunno, but I didn't see the video so I assume it's for single players...
the best you can do is simulate a chest ui with json ui and then just open that on the command call
can sum1 help the debugger extension isn't working for me
it says failed t connect when I do the cmd in game
How does that look like, kindly provide screen screenshot if you want someone to troubleshoot
world.afterEvents.playerSpawn.subscribe((event) => {
if (dimensionGenerated === false) {
dimensionGenerated = true;
for (let z = 100000; z <= 500000; z += 16) {
for (let offset = 0; offset <= 400000; offset += 16) {
if (Math.random() < 0.5) {
world.runCommand(`structure load mystructure:fieldtree ~${100000 - offset} ~500 ~${z}`);
} else {
world.runCommand(`structure load mystructure:fieldbase ~${100000 - offset} ~500 ~${z} `);
}
if (Math.random() < 0.5) {
world.runCommand(`structure load mystructure:fieldtree ~${100000 + offset} ~500 ~${z}`);
} else {
world.runCommand(`structure load mystructure:fieldbase ~${100000 + offset} ~500 ~${z} `);
}
}
}
for (let torture = 100016; torture <= 500000; torture += 9) {
if (tortureFirstRoom === false) {
world.runCommand("structure load mystructure:torturenormal ~100000 ~700 ~100000");
tortureFirstRoom = true;
}
const random = Math.floor(Math.random() * 25) + 1;
if (random <= 23) {
world.runCommand(`structure load mystructure:torturenormal ~100000 ~700 ~${torture}`);
} else if (random === 24) {
world.runCommand(`structure load mystructure:torture_exit ~100000 ~700 ~${torture}`);
} else {
world.runCommand(`structure load mystructure:torturechest ~100000 ~700 ~${torture}`);
}
}
}
});
Why does this literally not generate anything?
- see if youre getting anything from content logs
- you should try adding tiny stuff like
console.log("test")or anything to see if the checks are passing
Hmm but when there was an error with the command, it said not a valid function smth like that
....i just noticed youre doing runCommand on world...
its either entity, player or dimension
Bruh wtf am I doing
its ok
I was supposed to do overworld
common mistakes lol
Also, BTW how to add delay to for loop? Cause there seems to be an internal and watchdog error due to hang.
from that code?
Ye
then you should try runJob
its specifically made for big stuff like that
though i dunno how to use it, ill try searching for a few use examples
Me too. I have never really used it
Jus trynna make kinda dimensions using set structures
Because I need it to expand on both x sides as well
There is the method that runs on 0 ticks so you don’t need promises or await
https://discord.com/channels/523663022053392405/1365770249835909272
I made it so it just spawns the itemStack as an entity it gets killed and it drops its stored items then a getEntities() gets all the items that the shulker dropped
again, 0 tick it misleading, 0 tick is 0 ms and that is not possible
Does anyone know how to add a delay between each for loops? Cause it gives a 1053 ms hang error
You get it why do you need to correct me 0 ticks means that runs On Tick and doesn’t need a tick delay
and says does not have required privileges
simply modify the way you doing it
i mean, instead of writing faster code write smarter code
thats not how it should be used
make loop within job and yield every inter
you yield each piece and use the generator in runJob
function *doStuff(){
for(;;) {
yield stuff();
}
}
system.runJob(doStuff());
something like this
cause that is not benchmarking and no one says that.
no hard felling but if you want to share how fast it run just benchmark your script, it doesn't need a tick delay doesn't mean anything
world.afterEvents.playerSpawn.subscribe((event) => {
if (hasPlayerJoined === false) {
hasPlayerJoined = true;
nullTploc = event.player.location;
}
if (dimensionGenerated === false || dimensionGenerated === true) {
dimensionGenerated = true;
function torture(offset, z) {
if (Math.random() < 0.5) {
overworld.runCommand(`structure load mystructure:fieldtree ~${100000 - offset} ~500 ~${z}`);
} else {
overworld.runCommand(`structure load mystructure:fieldbase ~${100000 - offset} ~500 ~${z}`);
}
if (Math.random() < 0.5) {
overworld.runCommand(`structure load mystructure:fieldtree ~${100000 + offset} ~500 ~${z}`);
} else {
overworld.runCommand(`structure load mystructure:fieldbase ~${100000 + offset} ~500 ~${z}`);
}
}
function* tortureLoop(){
for (let z = 100000; z <= 500000; z += 16) {
for (let offset = 0; offset <= 400000; offset += 16) {
torture(offset, z);
yield;
}
}
}
function field(torture) {
const random = Math.floor(Math.random() * 25) + 1;
if (random <= 23) {
overworld.runCommand(`structure load mystructure:torturenormal ~100000 ~700 ~${torture}`);
} else if (random === 24) {
overworld.runCommand(`structure load mystructure:torture_exit ~100000 ~700 ~${torture}`);
} else {
overworld.runCommand(`structure load mystructure:torturechest ~100000 ~700 ~${torture}`);
}
}
function* fieldLoop(){
for (let torture = 100016; torture <= 500000; torture += 9) {
if (tortureFirstRoom === false) {
overworld.runCommand("structure load mystructure:torturenormal ~100000 ~700 ~100000");
tortureFirstRoom = true;
}
field(torture);
yield;
}
}
system.runJob(tortureLoop());
system.runJob(fieldLoop());
}
});
Now it doesn't even generate anything for some reason
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]
is this prone to duplication glitches?
world.afterEvents.playerInventoryItemChange.subscribe((event) => {
const { player, itemStack, slot } = event;
event.itemStack;
const customPlayer = globalThis.GlobalCustomPlayers.get(player.id);
if (customPlayer && itemStack) customPlayer.playerInventoryChange(slot, itemStack);
});
/* class CustomPlayer */
playerInventoryChange(slot: number, item: ItemStack) {
if (!item) return;
if (item.getDynamicProperty && item.getDynamicProperty("dusted")) {
return;
}
let changed = false;
const enchantable: ItemEnchantableComponent | undefined = item.getComponent("enchantable");
if (enchantable) {
const sharpness = enchantable.getEnchantment("sharpness");
if (sharpness && sharpness.level > 2) {
sharpness.level = 2;
enchantable.removeEnchantment("sharpness");
enchantable.addEnchantment(sharpness);
changed = true;
}
const protection = enchantable.getEnchantment("protection");
if (protection && protection.level > 2) {
protection.level = 2;
enchantable.removeEnchantment("protection");
enchantable.addEnchantment(protection);
changed = true;
}
}
if (changed) {
if (this.container) this.container.setItem(slot, item);
this.player.sendMessage("§eYour item's enchantments were set to a maximum of Sharpness II and Protection II.");
}
}
okay seems that it is
no idea how to fix it tho
it's hard to dupe the item but the risk is still there, any way i can fix it
Hello, is there any way of checking when chunks have loaded, and checking the location of said chunks?
No.
okay, thank you
Considering players technically are the only ones that can load said chunks. Yeah you could detect it
Structures load chunks.
Oh. Yeah...
I read into that, but I'm looking for a function/method that states "chunk X has been loaded" and then find the blocks in that. I mean i could in theory check the block radius that is in the players vicinity, but that seems messy and taxing
Well iirc. Bedrock loads chunks in a diamond shape... And for each player you could just store their current chunks position, then if it changes, get the new ones using a mathematical equation.
Otherwise it's basically a no, there's no proper api for chunks yet
Im sure i could use a maths equations, but im no mathematician so i will leave this on the backburner for another time
how can I convert this to the new applyKnockback
player.applyKnockback(di.z, -di.x, -3, 0)```
It's a VectorXZ now.
Documentation for @minecraft/server
ik a bit how but idk how to make it go sideways
const horizontalForceF = {
x: viewDirection.x * 5,
z: viewDirection.z * 5
}
return entity.applyKnockback(horizontalForceF, viewDirection.y * 0.5)```
Set X to 0 and Z to 5 or flip flop.
[Scripting][error]-TypeError: NaN value is not supported. Function argument [0] expected type: VectorXZ at <anonymous> (main.js:36)
this error appeares
cant put 0
What did you put?
const horizontalForceR = {
x: viewDirection.x * 0,
z: viewDirection.z * 5
}```
or u didnt mean like that
even when I put nothing it says that
Can you try just 0 and 5, dont multiply viewDirection.
already tried and still doesnt work
New format is
applyKnockback({ x: x * hStrength, z: z * hStrength }, vStrength)
instead of applyKnockback(x, z, hStrength, vStrength)
Yes they did that.
oh ok
Im guessing viewDir is NaN
it works fine im just trying to make it go sideways
And NaN times a number is NaN
Not a Number? But it literally is
Does anyone know why this doesn't generate any structure?
ohhh it's a magnitude now
oh wait
oh it's just {x, z}
welp
why does the useOn item event not work when interacting with cauldrons?
is xz normalized?
Can I modify item in cursor component to change the itemstack?
No.
sad
~500 and ~700 isn't a place where any blocks can be placed. Unless you have height increased?
Has someone made anything using the new inventory change afterevent ?
Seems promising especially for a possibility of testing for recipes like crafting
It is only for player inventory?
-# and hotbar
I believe this one is for any change, while there is a hotbar change after event as well just saw it in the log when going through the stable release lol
Could make gui in inventory now right haha
Now we have so many options
I mean it says player inventory change
Yeah player haha
You could detect player crafting with it i think
That's the cool thing, detect what was crafted in a way
Since your inventory changes with craftibg
Some custom class i suppose with the event
Just exclude item dropped and item storage amd all the events that consume items
Seem a bit janky tho, haha
An easy one is item pick up event
True!
Entity remove + that
Anyone know how to get the swing animation to play in first person when using an item and playing the animation, my animation only plays in third person for some reason.
Yeah, just add location for more accuracy
small shit