#help-development
1 messages · Page 394 of 1
Yeah but location in the bottom most line is not available. How do I get that location?
Do I need to do a loop?
Until you learn more about different data structures you should just start one runnable when the server loads
and let it iterate over your map every second. Performance wise this should not be a problem.
Then all you need to do is add and remove objects from the map. No need to handle hundreds of tasks.
What does that mean in words a normal person can understand
Start a Bukkit runnable. Schedule it to be run every 20 ticks.
On every run() call you do a for look on your map.
Start the task in you onEnable and never stop it.
Dont start any other tasks.
But how will that add an individual cooldown to all the scraplocations?
And every second you remove 1 from the counter?
But if I add a variable to my chestObject, I'd also have to fill in another argument when I try to add a location
ChestObject chest = new ChestObject(false, blockLoc, particle, cooldown, items, "cooldown argument?");
No
It loops
So you can harvest it, then it cools down, then you can harvest it again, etc.
no you don;t add another arg
the value is internat to he chest objewct
all it does is count down from the cooldown to zero
and then set isLootable to true again, right
you tick it every second
and restart the counter
yep
So that should go in my chestobject class?
yes
And how do I run it every second
you add a method to decrease/reset it
Yes I know that, but you need a method that makes sure that that method runs every second right?
Thats what I'm asking
That is what the task is for
you should have a task running that loops over your chests
ohh alright
so I need a task in a seperate class that runs the method in the chestObject class
in that task you loop over chests, decrease counter, check if zero, flag chest as lootable and reset counter
oh
it shoudl also trigger the particle
Dont necessarily need a separate class. You could put the runnable inside the chest object that gets executed automatically when you create the object.
Yes you can also do this too. I dont know their overall layout or goal. So you know gives them more options for flexibility
Yeah we can do that sometimes lol
Ill just do this:
- Add a method to ChestObject called Cooldown, that, when run, will decrease the cooldown time by one if it's not isLootable, and will check if it's 0 (then reset it and set isLootable to true)
- Add a task in a seperate class, maybe onEnable, that calls Cooldown every second
- Go over all my chestObjects in my spawnParticle class, check which are isLootable, then add a particle there.
I know what you guys are going to say right now
dont put it in onEnable
Honestly all the logic should be contained within the ChestObject
...
well that's what makes my brain fry. What I posted above still makes it fairly understandable to me
And it has a method called tick()
Your runnable just calls tick() every second on every ChestObject and does nothing else.
is tick() a standard method called every tick then?
This is what i am accustomed to doing, but i can see it also making sense having a single task too. It just depends on how its structured or the overall goal.
Usually you would call it every tick.
It depends on how you structure your clock cycle. If your lowest time frame is one second then
you call it every second.
Just remember that your Object now needs to know its own location as a field.
Above they have a blockloc as an argument so i assume they are passing in a location already
?paste
What about this? https://paste.md-5.net/zovoqimupu.cs
Garbage
Using reflections for this is bad. And those reflections are not even cached.
So how I am supposed to avoid this
I don't have the player texture
What version are you on?
I just have the texture value, like the one you find on HeadDB
1.12.2
Well then you have to use reflections. Search for an old tutorial from a few years ago.
Wasn't my snippet good for this purpose?
Pass true to your update method and try again
try getDeclaredField
thats some weird salad
That's not salad
Broccoli
is there anyway to get all pdc on an item, types, values, keys etc without knowing its specific type or needing to call get for each type on one key without needing to use NBTBase stuff
and whats the weed plant doing there
Rotten Broccoli
A kinda of sweet salad
pov: the silent kid in minecraft
There is sadly no simple way of doing that
for context im trying to make an ItemStack type adapter for gson and dont want to jank stuff that doesnt need it

So you want to filter out certain pdc entries when serializing?
NBT is the way, I mean you could set a sort of invisible value like on the lore which is unique for each item and then you associate a value on a db
i managed to do it on yaml with NBTBase and jank methods
but sadly gson doesnt have addProperty(String key, Object value)
Hellooar How do set motd to middle with gradient
What about this?```java
private ScheduledExecutorService executor;
public void startCooldownTimer() {
if (!isLooted) {
isLooted = true;
executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(() -> {
isLooted = false;
executor.shutdown();
executor = null;
}, cooldown, TimeUnit.SECONDS);
}
}``` I call it when I right click a block that is registered as ChestObject
and thats within what class?
In the ChestObject class
?scheduling tho
I always use NBTAPI
if (!itemMeta.getPersistentDataContainer().getKeys().isEmpty()) {
PersistentDataContainer pdc = itemMeta.getPersistentDataContainer();
Map<String, NBTBase> stringNBTBaseMap = new HashMap<>();
stringNBTBaseMap.putAll(Utils.getCustomDataTags(pdc));
stringNBTBaseMap.forEach((key, value) -> {
configurationSection.set("pdc." + key + ".type", value.getClass().getSimpleName().toUpperCase(Locale.ROOT).replace("NBTTAG", ""));
configurationSection.set("pdc." + key + ".value", Utils.convertToCorrectType(value.toString(), value.getClass().getSimpleName().replace("NBTTag", "")));
});
}
``` that was a very fun method to somehow come up with
ig you just want to execute logic in there that runs every second
it has some goods methods to serialize stuff
create a manager class that actually calls those methods every second
hmm right good point
i wonder if i can store an entire pdc container with b64 , idk how i would deserialize it
7smile7 is gonna come up with a genial solution, i feel it
You are going to park a metric ton of system threads just to enable some cooldowns.
Its nice that you look into other ways of doing this, by all means keep exploring, but you
cant create a new executor service for every single running cooldown.
Also: Your variables are not thread safe. If you want to do it this way:
- Create 1 Executor and schedule all your cooldown reset tasks on this executor
- Make your cooldown variable an AtomicBoolean so that you dont run into threading problems
Hmm alright lets not do it this way then. Seems too complicated
Fourteenbrush mentioned schedulers?
Yeah but you are also running an ancient version of spigot so...
NBT is just JSON though. :p
isnt all the data on an item stored in json
i was just realising that
can someone explain why this isn't working? do strings get generated at compile time?
I love ancient things with cobwebs
Who is currently serializing recipes from mojang? Tell that to him. NBT is almost Json but not quite. Its super weird.
You didn't initialize dbname. You just declared it.
wtf is a field so is set before yoru constructor runs
dunno what the point of that isLooted is but ig you want smth like this:
class LootThingie {
boolean looted;
void tick() {
looted = false;
}
}
class LootManager() {
List<LootThinie> loot;
scheduler.runTaskTimer(plugin, () -> loot.forEach(LootThingie::tick), 0, 20);
}```
im asking about the 'always' part. shouldnt it change in the class initialization?
where you just call tick on the loot thing every second, probably want to remove it too
i wonder how i can get the entire nbt json of an item
im feeling your pain, deserializing recipes goes even more brr
Elgarl and I came up with something similar when we explained the general idea to him earlier 👍
It's just the phrasing. It will always be null since it has not been initialized yet. Which if not set, will be null during class initialization.
You could just use the serializer from mojang.
isLooted shows if the block can be looted or not, and shows if it's been looted or not
they have a serializer?
whats it called
hello? If there's only one constructor, the class can only be initialized with that specific constructor. How can it still be 'always null' then?
if the constructor sets that value?
it do work
your ide will just complain because at the given time its null
you would need to reinitialize your var after object creation
arent fields with an explicit intializer initialized before fields that are initialized in the constructor?
It's probably just a general check then. It is just a warning after all. If you define it in the constructor and only have one constructor then there should be no issue. It might be that the warning is also checking against an internal empty constructor instead of the full class context.
What about this. It gets run whenever the block gets looted. The runtasktimer makes sure it gets run every second right? java public void startCooldown() { if (!isLooted) { return; } countdown = cooldown; new BukkitRunnable() { @Override public void run() { if (countdown <= 0) { this.cancel(); isLooted = false; } else { countdown--; } } }.runTaskTimer(plugin, 0, 20); // run every second (20 ticks) }
why's there no sql spigot tutorial apart from that 2015 thing urgh
it would tick once per second, but the isLooted reference might be shaky
What about this one? Last updated 2022
https://www.spigotmc.org/wiki/connecting-to-databases-mysql/
Why would the isLooted reference be 'shaky'?
isnt it static?
no?
i saw that one but thats sql/maria, not sqlite
Oh, sqlite.
ye i need it local
dont have an actual db server available
Do you need the data in a readable form?
works for all of them no?
nah
Did you have issues with the thread? Cause I used that as the base for my implementation.
does mojang somehow also has a public deserializer for their client recipe jsons? 👉👈
are you saying all i need to do is create a .db file and point a connection at it?
Pretty much yea.
for sqlite? yes
Then this serializes the ItemStack to a Base64 String:
public static String itemStackToBase64(final ItemStack item) {
try {
@Cleanup final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
@Cleanup final BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
dataOutput.writeObject(item);
return Base64Coder.encodeLines(outputStream.toByteArray());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
And this deserializes it again:
public static ItemStack itemStackFromBase64(String base64) {
try {
@Cleanup final ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(base64));
@Cleanup final BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
return (ItemStack) dataInput.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
Oh probably. But id have to dig through nms 
uh oh
currently got 300 lines of code to deserialize certain shaped recipes
and that only works half of the time
try with resources ig
How do set motd to middle with gradient
for lazy fuckers
Help
uhh context please?
Just all the try, catch, finally for auto closable objects
fun
I have this motd with gradient color but its not centered even tho it has spaces already
I use mctools
Just use kotlin hehe
?img
Not verified? Upload screenshots here: https://prnt.sc/
👋
dang github
i like to do pointless things https://github.com/The-Epic/EpicSpigotLib/blob/master/src/main/java/me/epic/spigotlib/storage/SQliteConnectionPool.java
Btw you can also use Spigots serialize method which serializes the ItemStack to a Map<String, Object> and let Gson have its way:
public static String itemStackToSpigotString(ItemStack itemStack) {
return GsonProvider.toJson(itemStack.serialize());
}
public static ItemStack itemStackFromSpigotString(String str) {
return ItemStack.deserialize(GsonProvider.fromJson(str, new TypeToken<Map<String, Object>>() {}.getType()));
}
But this breaks with PlayerHead items.
its very fun
Does anyone kno
Ive been restarting my server to see if something changes
Nothing happens
ah
heehee
AH NVM
it probably also drops enchantments
IT DOESNT HAVE SPACES but I have put spaces already
._.
wlep how
Any recommendations
I use purpur
okay im back to being confused how gson works
trying the b64 thing first and im very confused how to get a value from a JsonReader
just use jsonobjects
but how
implement JsonSerializer<ItemStack> and optionally deserializer instead of typeadapters
i had that earlier on my other method
json objs are a lot better
not using the reflective stuff of gson tho
as i cant inject any context into a typeadapter
do i need to in.beginObject before parsing
you just told you were using jsonobjects
Can anyone please help me fix my entire plugin? Nothing works.
When I do /sc add SCRAPE 5 sand, it says "location added" in the chat, but when I do /sc list it says that I dont have locations added yet.
When I rightclick a block I get an error longer than godzilla's male-parts
No particles show up when I try adding something. Here's the code
https://paste.md-5.net/upiladotub.java - Particle Handler
https://paste.md-5.net/itawicemey.java - ChestObject
https://paste.md-5.net/igalamazix.java - EventListener
https://paste.md-5.net/witifijefa.java - AddParticleCommand
https://paste.md-5.net/bicepudobu.cs - error 😠
minimotd prob works for what you want
The space keeps getting removed
💀
Will “ works
What do u call thee
These
Lol
imagine making code that actually works
this is not c#
now to add this to my lib so i never have to remember it
?conventions
and change my toB64 methods
oh really?
shit I think Im in the wrong department
I give up
this code can suck my ass
Oh, you guys use base64? xD
i was writing a normally serializer that saved the data readable then got to pdc
Right, did you want it to be edited by humans? I usually just dump the xmaterial name, the amount and the root nbt tag compound into a byte array through a DataOutputStream and call it a day, xDD.
i started this like 2 days ago i dont remember what i wanted lol
just some form of item stack type adapter
Adapter? That sounds like something mediating between versions. Were there ever any breaking changes on NBT keys? I'm actually not sure...
gson type adapter
Oh, right, sry, xD
ParticleHandler pHandler = new ParticleHandler(); shoudl be a field not a local variable
wdym with a field?
You also have two, one in yoru onCommand and one in your event listener
you shoudl only have ONE particle handler
hmm I see
But then how should I cross reference them
?di dependency injection
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
Alright so I get what dependency injection is, but implementing it in code still fries my brain. So far I've turned pHandler into a field in the eventListener class.
But how I can access it in onCommand still confuses me
😭
?
I recommend checking out the examples of the linked page
I did
and I read the thing
and asked AI to explain it to me lol
I get what it means after chatgpt explained it to me like Im a 5 year old
but implementing it in code is just.... weird imo
Well its simple, create an instance in for example your plugin class
And then create a getter in that class
Then every class / object that has a reference to your plugin instance can call that getter to retrieve the instance of the thing you want
All of that just to pass 1 variable
You could also pass the variable directly in the constructor
You theoretically don’t need to use a getter there, but it might make things easier if you want to use that instance somewhere else
I only need to use it in onCommand and ther other class afaik
Yeah then create a field for that class in your command and your listener
Create the object in your plugin class
And pass it to the command and the listener via the constructor
Ah I see you don’t even know the basics of Java yet
I can fully recommend the introduction / wiki of w3: https://www.w3schools.com/java/
?learnjava
Here are some links to get you started on learning Java:
- https://www.codecademy.com/learn/learn-java
- https://www.sololearn.com/learning/1068
- https://www.learnjavaonline.org/
- https://programmingbydoing.com/
- https://docs.oracle.com/javase/tutorial/java/index.html
The last one is the only official one, however some of those concepts assume that you already know a bit about programming.
They should add w3schools to it, they explain it step by step - is easy to understand and free ofc
I think its fine tbh
I dont plan on learning java though lol. I just needed to make quite a simple plugin
The bascis are enough to get started imo - I learned everything I can today by myself mostly through trial and error
Back then it would‘ve been great to have w3schools xD
The basics of w3 help a lot understand other sites imo - so its a good starting point.
I think the official website is hard to learn from
Yeah
Idk if something changed since I started to learn Java
Probably did x)
(Hopefully)
Welp then it didn’t
Could anybody tell me what's the difference between the method dropItem() and dropItemNaturally? I did a little research but I don't finish understanding it.
If I remember correctly dropItemNaturally will give it random velocity
While dropItem doesn’t
the offset
basically dropped with an extra touch
in terms of efficiency is there much difference between them?
none
ok, ty guys
Well, not none, but it's negligible. Except for when you want to drop a thousand items all at once, xD.
yeah no, none.
yeah, that's not my case XD
@EventHandler
public void onBlockBreak(BlockBreakEvent e){
Block b = e.getBlock();
if (b.hasMetadata("placed") || !SpecialOre.FOUNT_ORE_MAP.containsKey(b.getType())) return;
NosamPickaxe nosamPickaxe = NosamPickaxe.getByItemStack(e.getPlayer().getInventory().getItemInMainHand());
if (nosamPickaxe == null) return;
SpecialOre ore = SpecialOre.FOUNT_ORE_MAP.get(b.getType());
int random = ThreadLocalRandom.current().nextInt(100) + 1;
if (random > nosamPickaxe.getProbability(ore)) return;
b.getLocation().getWorld().dropItemNaturally(b.getLocation(), ore.clone());
}
does it look clean for u guys?
Looks cleaner than my bedroom
lol
dont do two map lookups
ugh
Using contains instead of get with null check for non-null valued maps 
thats what im saying
Yep, was just clarifying. It's not so clear for people why that's two lookups. "I was only calling contains, not get", xDD
What about this?
public class EventListener implements Listener {
private final ParticleHandler pHandler;
public EventListener(main plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
pHandler = new ParticleHandler();
}```
```java
public class AddParticleCommand implements CommandExecutor {
private final ParticleHandler pHandler;
public AddParticleCommand(ParticleHandler pHandler) {
this.pHandler = pHandler;
}``````java
public final class main extends JavaPlugin{
@Override
public void onEnable() {
registerCommands();
new EventListener(this);
ParticleHandler particleHandler = new ParticleHandler();
particleHandler.spawnParticlesEverySecond(this);
}
private void registerCommands() {
ParticleHandler particleHandler = new ParticleHandler();
Objects.requireNonNull(getCommand("sc")).setExecutor(new AddParticleCommand(particleHandler));
}
why are you using naming conventions and suddenly not
and dont create particle handlers everywhere
3 times
only create the in the main class
somethings wrong with main
and pass them to the listener and command
k
What about this? Im pretty sure Im only instantiating a single ParticleHandler
Yeah your fine with this one
Alright, now time to fix the other 529329104 errors
What data does particle handler hold
At the current rate, it will take me approximately 529329104 * 2 / 24 = ~44.110.759 days
ah shit
💀
I was gonna say if it doesn't hold any data just use static methods
Then you ain't gotta worry about unnecessary DI which can get long and annoying
idk man. im just going to test this code and see what errors I get
If I dont get any errors Ill jump out of my window
Alright, heres my observations:
/sc add SCRAPE 5 sand - no particles, no error. It says it added it to the list
/sc list - works. no errors
/sc remove - works. no errors
When I right click, it says "looted block" and I get no errors, somehow.
This is not looking good
Ah shit it's working
@tardy delta it's working 🥹
Only thing is, particles arent working
Oh well it's only like 50% of my plugin
What is that
public void spawnParticlesEverySecond(Plugin _plugin) {
plugin = _plugin;
BukkitRunnable runnable = new BukkitRunnable() {
public void run() {
for (Map.Entry<Location, ChestObject> entry : chests.entrySet()) {
Location location = entry.getKey();
if(!chests.get(location).isLooted()) {
Particle particle = chests.get(location).getParticle();
Objects.requireNonNull(location.getWorld()).spawnParticle(particle, location, 7, 0.1, 0.2, 0.1);
}
}
}
};
runnable.runTaskTimer(plugin, 0L, 20L);
}```
Man I dont know anymore. It works
How
idk man
Ye
"main plugin" refers to the instance of the main class that extends the JavaPlugin class. It is used to register the EventListener instance to the Bukkit event system, so that the EventListener can listen to events being triggered by the server.
it uses a feature called "lambda expressions" in Java.
A lambda expression is a way to define a method without using the traditional method declaration syntax. Instead, it provides a shorthand way to write a single method that takes in one or more parameters and returns a value, if necessary.
it runs in minecraft so it must
Bro I know what lambda is
brothers i am the master builder what is this
Why u sending definitions of everything
to infrom you
I feel like I'm talking with some form of AI
Because I like to
I took a "how human am I test"
And Im actually an android
so you're correct
thats smoldring with ezxcitment
It also said that I can only get a girlfriend if she's severely disabled and blind
declare one chest object from map#get and then use this instead of always get it from map
yay wheel chair photo shoot
Go away
ight thats rude my man
And what would that be in words a normal human can understand?
makes a disabled joke and then bashes someone for chiming you a whole bitch
yes
atleast you know
But that wouldnt work right, because every chest object is different
And all different chest objects are stored in a Map
with a location to make it easy to reference them
ChestObject chobj = map#get
If chobj#isLooted
...
Or there it will be entry#getValue
if(!chests.get(location).isLooted()) entry.getValue() is the ChestObject. no need to use teh map again
you are already looping the Map so use teh entry
I was already wondering if there's a better way because it looked like a bad piece of code
if (!entry.getValue().isLooted())
for (Map.Entry<Location, ChestObject> entry : chests.entrySet()) {
if (!entry.getValue().isLooted()) {
Particle particle = entry.getValue().getParticle();
Objects.requireNonNull(entry.getKey().getWorld()).spawnParticle(particle, entry.getKey(), 7, 0.1, 0.2, 0.1);
}
}```
I replaced the locations with entry.getKey instead of making a new var for location bcs it didnt seem very organizd. I also changed the particle thingy
yes but remove the Objects.requireNonNull( its annoying auto fix suggestion by inteliJ
it's always wrong
all it does is stop teh IDE complaining but fixes nothing
otherwise it can throw null errors
hey i got a problem, in my Spawn.java i got a "spawn" variable and i want to use it in my Listener.java so how do I do ?
Pass it into your Listener constructor
i found this code snippet online
try{
PreparedStatement ps = connection.prepareStatement("SELECT * FROM " + table + " WHERE playerUUID = ?");
ResultSet rs = ps.executeQuery();
close(ps,rs);
}
```but where does the argument for the statement come from? There's nothing passed to it, so how does it find the UUID?
Yeah, dont do that. Thats not what he needs.
?di
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
Read this
What is Spawn.java? you should instantiate it onEnable and pass it into your Listener
gonna need more context than that
they never set the uuid
?paste
Again
that error
It just keeps appearing
every single time
Everything works apart from the particles
i wanna override the /kill-command for custom messages and everything works fine when in survival but in creative it doesn't play the little screen jiggle for taking damage (which it does with the normal /kill-command) and it's freaking me out. Does someone know how to fix that?
ParticleHandler.java:57
public boolean CheckLoc(Location loc){
return !chests.get(loc).isLooted();
}
the return
so that must return null huh?
it means that Loc does not exist in the Map
oh
@tardy delta do u recon the purpose of that is to check if the field is present and spit out an error if not?
Did you normalize it before checking?
I normalized it in the onCommand, where I add it to the ChestObject
is the loc you pass to CHeckLock a normalized location?
spawn.java is the file where i created the /spawn command (and i wann do the /setspawn)
oh
good spot lol
Can you send the spawn class and your onEnable?
At first get chestobject and if is null return false else return chestobject#islootted
See, my brain that operates on a single braincell can't see those things as fast as you can
Round it
it floors an int
@Override
public boolean onCommand(CommandSender sender, Command cmd, String str, String[] args) {
if(str.equalsIgnoreCase("spawn")) {
if(sender instanceof Player) {
Player player = (Player) sender;
Spawn spawnClass = new Spawn();
Location spawn = new Location(Bukkit.getWorld("world"),0,1000,0);
player.teleport(spawn);
}
}
return false;
}
}```
If I change a plugin in my plugin folder, and type /reload whilst keeping the server online when changing the plugin folder, will it reload the plugin folder?
oh ok
It doesn't round it floors, which is basically like removing the decimal. It takes a float and always rounds down to the nearest int.
Your spawnClass is useless. I does exactly nothing here.
yeah
isnt that bad though
because it can change the block I specified
Or not?
wait no it wont do that
ik but someone told me and i was trying to understand why
yes
Yep
or 1.99 to 1.0
idk where you got that from
like i said 2015
all other spigot posts refer to a library
The opposite would be ceil (ceiling) which would make 1.33 2
Alright so now I dont get any errors, but I also dont get any particles
man just forgot or smth
What is in the Spawn class? and what are you using it for? I see no reference to it after you create it.
nothing it was just a test
Ok so what exactly are you trying to do?
i am trying to take the variable spawn and use it on another file
So your question is just how to reference a variable in another class?
yes
getter?
First off, you should not be creating Spawn in your onCommand unless you need a defferent version of Spawn for every command execution. Variables like that should be declared at the top of the class. And if you want to use the same instance of Spawn in multipole classes put it in your main class and pass it into your other classes.
If you for some reason want/need the variable to be initialized in your CommandExecutor class then make a getter and pass a reference of your CommandExecutor class to the other classes you want to use it in.
oh ok
like i need it to be in command executor because after i am gonna create a /setspawncommand
You should have 1 command per executor class
Initialize Spawn in your onEnable and pass it into the command executor classes that you want to use it in
Anyone want to be a developer for me must be really experienced for coding and scripting.
wrong channel
What channel do I go In?
?services
If you wish to request or offer development/art/building/administration services, please do so at https://www.spigotmc.org/forums/services-recruitment-v2.54/
thanks!
Reload
You can also ask on coded reds server, they have a dev request channel
I did
Is it possible if you can direct me In DMs?
Yeah
can i pass instance like this?:
public static Duels plugin;
public GUIManager(Duels plugin) {
GUIManager.plugin = plugin;
}
no plz
why
i initialized it in my onEnable so after how do i use it in other classes
public static Duels plugin;
public GUIManager(Duels plugin) {
this.plugin = plugin;
}
will that work?
Yeah
But why make duels static
The idea of that is that you can have an instance of it
Remove static
because the method i use it in is static
Pass it into your constructor for the CommandExecutor classes
but then how do i access the method from other classes?
private final Duels plugin;
public GUIManager(Duels plugin) {
this.plugin = plugin;
}
You pass an instance
To each class you need
Exactly how you just did
how
Why do so many people struggle with this... smh
Remember that every time you call a new MyClass() the constructor gets called
?paste @charred blaze code
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
If you want help, then use the resources that have been given to you.
When I rightclick a block that isnt a ChestObject I get this error
https://paste.md-5.net/esacilaweh.cs - error
https://paste.md-5.net/togoloziza.java - interactionhandler thingy
so i do it like this?
getCommand("duel").setExecutor(new DuelCommand(new GUIManager(this)));
so how
Show me your project structure
Like a image
Ok so
All you do
I assume
You want to be able to use GUIManager
From a command, correct?
yeah
Duels.java
GUIManager manager;
public void onEnable() {
this.manager = new GUIManager(this);
getCommand("duel").setExecutor(new DuelCommand(this, manager));
}
DuelCommand.java
GUIManager manager;
public GUIManager(Duels plugin, GUIManager manager) {
this.plugin = plugin;
this.manager = manager;
}
I didn't use an ide so might be typo
@charred blaze
No
Literally point 2 in Dependency injection
God no
lol
why cant i do it like i did above?
What I sent is the most used by far, it's the most correct method
Because you're mixing instances
Seriously everyone in this channel right now needs to read this, PLEASE
so what
?di
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
Greened you asked how to do it. I provided you with the best way
im not very good in english
?di @quaint mantle
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
Doesn't matter if you need 1 or 10 instances, di
read what
di?
Look up java dependency injection in your native language on YouTube then or just translate the page
yes
Ahh alright
However an unjustified reason to use a static singleton would be if your system is only ever going to need one instance of a class.
Why not use object oriented programming in a language that's object oriented... w/e
we are only 2m on our country. who would make video about java injections? :/
Did you type the code I sent?
then translate the page
What's your native langauge?
You will understand once it works, just see what it does
translator is so good that i cant even read
?di
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
werent i doing the same thing????
in my code?
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
?di
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
?di
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
?di
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
Everything you need to know is right there
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
you just created a variable with same code
didnt you
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
I stored the instance of the variable in the main class
why
So you can pass it to other classes that you will need
I found that chatgpt is usually better at explaining things like this. I usually use this server for when AI doesnt know it
Because that's how object oriented programming works
I can, It's quite simple. But i don't need to when someone has already written a very clear article on it that you refuse to read
Ok, explain it then
Tell me your question exactly
because now all of you are just wasting time
I gave up at this point
So I've just been spamming di cause he took it personal
?di
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
However an unjustified reason to use a static singleton would be if your system is only ever going to need one instance of a class.
Can this guy not read?
W/e just blocked him cba just flooding the channel while refusing to read
?di
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
Static on the other hand is not object-oriented and is in Java a way to declare things as global. While it may seem handy at first being able to use something like MyPluginDataManager.getInstance() all over your classes, it will also leave some devastating issues. Any class which directly relies on that static singleton will be tightly coupled to that instance of which the static singleton returns. This is inherently bad as it will be difficult to unit test an instance of that class, since we will inherently test the static singleton as well. Secondly, we will not be able to reuse the class for another MyPluginDataManager instance. Thirdly, by using a static singleton you have complexified your code architecture.
can you just explain why my code wont work?
I do, seems like you don't actually understand how to read
😦
I explained
Ok I'm out guys, there is no hope for you
I said, you want to keep an instance of GUIManager in your main class. and pass that as a parameter to each class that you will need to use it from
cant i just pass it to the command class without storing it? just asking
GUIManager manager; <--------------- this
public void onEnable() {
this.manager = new GUIManager(this);
getCommand("duel").setExecutor(new DuelCommand(this, manager));
}
i know i know
You can but then when you need it in a different command
You won't be able to pass the same
you just needed to tell me that
And you don't want to make different instances for that
I did
I said, you want to keep an instance of GUIManager in your main class. and pass that as a parameter to each class that you will need to use it from
So you can pass it to other classes that you will need
mb was answering the guy about ?di
i dont know why people write that non clear. couldnt you just say that spamming new and new instances is bad?
Because there's a different between english talk and java talk
Of course I could say bad, but just saying "it's bad" isn't an explanation
Think about new this way
this isnt a explanation either
"why?"
I disagree that the GUIManager should be singleton. Singleton is a bad design pattern that has many drawbacks and disadvantages.
Some of them are:
Singleton violates the single responsibility principle by controlling its own creation and lifecycle.
Singleton introduces global state and tight coupling, making the code hard to test and maintain.
Singleton can cause concurrency issues and memory leaks if not implemented carefully.
Singleton can break modularity and scalability, especially in a distributed or clustered environment.
Instead of using singleton, I would suggest using dependency injection or service locator to manage the GUIManager instance.
These patterns allow you to decouple the GUIManager from its clients and control its scope and lifecycle more easily. They also make your code more testable and flexible.
Are you gonna keep complaining or is your question answered? Yes it's bad
Jan
Give up
whats going on here
He's been going at it for 15 minutes
Don't worry i used bing to answer him
singleton 
xd
does bing really has AI?
rather make it static
how do i turn it on
Finally someone with some brain cells, careful though, they won't last long in this chat
?bing
Bing your question before asking it:
https://www.bing.com/
I mean that guy was so committed to using a singleton lol
I love that you blocked him
¨Don't worry i know about spigot
Bro there was no point
He just doesn't understand
I wish I didn't get the option to "show message"
a singleton doesnt fail. a singleton is just a bad design you should dodge whereever you can.
I disagree that most of the reasons are on a large scale. They can affect any application that uses singleton, regardless of its size or complexity. For example:
Singleton can violate the single responsibility principle even in a small project, making the code less cohesive and more coupled.
Singleton can introduce global state and tight coupling even in a simple application, making the code hard to test and maintain.
Singleton can cause concurrency issues and memory leaks even in a single-threaded environment, if the singleton object is not thread-safe or has references to other objects that are not properly released.
Singleton can break modularity and scalability even in a standalone application, if the singleton object depends on external resources or configurations that are not consistent across different environments.
Just because it can fail doesn’t mean it will is not a good justification for using singleton. Anything can break if not implemented correctly anyways is also not a valid argument. It implies that we should ignore good design principles and practices and rely on luck or trial-and-error. That’s not how we write reliable and maintainable software. We should always strive to use the best patterns and techniques for our problems, and avoid those that have proven to be problematic or harmful. Singleton is one of those patterns that should be avoided as much as possible.
what differences does it has to google?
its bing
you need to opt in
opt? wdym
lmao
It's a thing in the dev branch of the edge browser
People use edge?
how do i
get the dev branch of edge
and click the bing icon
then opt in
join the waitlist
and itll enable the AI?
why
Bing with AI is going to be wild
xd
Cause it's still a dev feature
Not sure exactly how that's going to work
who?
Microsoft put in so much money into it
Soon it'll beat everything else
Just wait
so it will be chatgpt vs bing
bing gonna destroy
yeah
Not for long
so chatgpt vs chatgpt
^^
unknown error exception
Microsoft invested like 10b in OpenAI
Well yeah obviously
though a model that can search the net.
mb I worded wrong
Does that mean they’ll add chatgpt to minecraft
To do what?
Yoo
not really
maybe
probably not
No use for it probably
chatgpt plugin when
ChatGPT for mob ai
new random feature coming to 1.20??
Don’t question it
Jan does spigot start working on 1.20 before release?
Do we know what we're getting in NMS and spigot?
As in new
Nope
I mean, new stuff
It’s just minecraft
I wonder what we can do in 1.20 that we can't do rn
Can't you technically look at nms for the snapshots?
Yes
I think chatsonic can do it for you
It would just be without mappings
Singleton is bad not only because it introduces a global state, but also because it violates other design principles and practices. People are not scared of a global state, they are aware of its drawbacks and risks. Some of them are:
Global state makes the code less predictable and more prone to errors, as any part of the code can change or access the state without any control or restriction.
Global state makes the code less testable and maintainable, as it introduces hidden dependencies and side effects that are hard to isolate and mock.
Global state makes the code less reusable and extensible, as it creates tight coupling between the singleton object and its clients, making them hard to replace or modify.
Just because it can doesn’t mean it will is not a good justification for using singleton. It implies that we should ignore good design principles and practices and rely on luck or trial-and-error. That’s not how we write reliable and maintainable software. We should always strive to use the best patterns and techniques for our problems, and avoid those that have proven to be problematic or harmful. Singleton is one of those patterns that should be avoided as much as possible.
I’d like to disagree with the modularity and scalability as well due to that not having anything to do with the pattern rather or how it’s implemented is also not a valid argument. It implies that we can implement singleton in a way that does not affect modularity and scalability. However, that’s very unlikely or impossible in most cases. Some examples are:
Singleton can affect modularity if the singleton object depends on external resources or configurations that are not consistent across different environments. For example, if the singleton object connects to a database or a web service, it may break if the connection parameters change or if the service is unavailable.
Singleton can affect scalability if the singleton object is not thread-safe or has references to other objects that are not properly released. For example, if the singleton object holds a lock or a cache, it may cause concurrency issues or memory leaks if multiple threads access or modify it concurrently.
Therefore, using singleton can have negative impacts on modularity and scalability regardless of how it’s implemented.
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
?di
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
?di
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
bruh
You can remap the snapshot jars
I have him blocked but jan still going at it
jan brought his big brother bing
xd
zacken just take the L man...
Jan you working on any projects rn?
guys I can use a variable in another file when I initialize it in the top of a class but when I initialize it in onEnable() i cant use it
No i am in clinicals
which one is to use?
last one
Can anyone help me sort server plugins, Featherboard, Tab, And Oraxen I need help working with them and also to add prefix tags such as oraxen better prefixes are in the files to!
I think #help-server is more appropriate for that
lemme guess, i gotta handle a few thousand files more
So I have this code that lets me add a block to a list, that adds particles to it and makes it "lootable" (with a cooldown). Thing is, I want to give players a random item when they right click it. The random items are specified when using the /sc add command:
switch (args[0]) {
case "add" -> {
if (args.length == 4) {
// convert args[1] to particle
Particle particle = Particle.valueOf(args[1].toUpperCase());
// convert args[2] to int
int cooldown = Integer.parseInt(args[2]);
// convert args[3] to List<ItemStack>
List<ItemStack> items = new ArrayList<>();
ChestObject chest = new ChestObject(false, blockLoc, particle, cooldown, items);
pHandler.AddLoc(chest, sender);
return true;
}
sender.sendMessage(ChatColor.RED + "Incorrect usage! Simply look at the block you want to add.");
return true;
}```
My question is, how do you type in the items in-game?
Using /sc add EXPLOSION 10 sand,grass doesn't work
/sc add EXPLOSION 10 sand, grass also doesnt work, so what does?
How can you fill in multiple items (ItemStack) in a command
private final List<ItemStack> items;```
place your bets, will it do it
lel
eh not exactly
ew
Split the arg on “,” and then parse each part through Material.matchMaterial
let's torture it
Oh no
lol I actually got it to make a fully functional plugin after enough iterations. It was horribly coded, but functional. It's actually pretty cool to see how it combines what it knows in a new context. Some of it's solutions for things are so different than what I would come up with
yeah that's what i wanted to see
yeah it's fun to use for non-serious purposes lol
whats wrong with this code
You need to add a null check for "org.bukkit.event.inventory.InventoryClickEvent.getCurrentItem()"
i already do
have it
look in the screen
Send it in a code block or pastebin
you mean whole click event?
oh hell naw
wtf is this boolean isBowEnabled = true; boolean isTotemEnabled = true; boolean isGPEnabled = true; boolean isNotchEnabled = true; boolean isPotionsEnabled = true; boolean isShieldsEnabled = true;
// convert args[3] to List<ItemStack>
List<ItemStack> items = new ArrayList<>();
String[] itemStrings = args[3].split(",");
for (String itemString : itemStrings) {
Material material = Material.matchMaterial(itemString.trim());
if (material != null) {
ItemStack item = new ItemStack(material);
items.add(item);
}
}```?
Is that what you meant
i know
all of this is scuffed
IKNOW
why
because you never set the meta back
you just get a new meta, edit it and throw it away
oh right
also switch exists
this is a bunch of boilerplate
and never check the inv by the title
Good god it just gets worse the more you look at it
what does
I'm sorry but i think you need to just start from the beginning lmao
xD
does .getSlot start from 0?
Yes
All arrays start at 0
why
you mean
variables?
is enabled ones?
i already know about them
its in my todo list
You should read this https://www.spigotmc.org/threads/a-modern-approach-to-inventory-guis.594005/#post-4553427
your current structure isn't really scalable
Could someone who knows sql translate this please?
<stack trace here>```
code:
```java
Statement s = connection.createStatement();
s.executeUpdate(CreateIfNotPresentStatement);//<Error here
the statement is
CREATE TABLE IF NOT EXISTS "+table+" (" +
"playerUUID CHAR(36) NOT NULL," +
"number INT NOT NULL" +
"inventory BLOB NOT NULL" +
"PRIMARY KEY (playerUUID)" +
"CONSTRAINT vConstraint UNIQUE (playerUUID, vaultNumber));"
wait
Put a space at the end of your strings to ensure that when they get concatenated, you aren't joining words accidentally.
what about this one
alright it wasnt the not anymore existing slotNumber one
please read it someone
hmm if i needed a hashmap with always 379 elements, would i use new HashMap<>(379, 1) or not?
was one of the problems, but not the main one
it now says inventory instead of NULLinventory
stack trace still points to the executeUpdate line
wtf
switch to new ui
Well, what line is it saying the problem is now?
still Statement::executeUpdate(CreateIfNotPresentStatement);
When trying to place the head, somehow it doesn't fill the gap between the block
Any ideas?
A hashmap that needs to be limited to 379 elements? Or must contain 379 at all times?
use hex colors
But i need the animation?
use mvdw
you should really ask this in #help-server
IS it possible if we can chat in dms
no
it will contain 379 elements all the time, they will be loaded on startup and after that, the map is readonly
I think you are also missing commas after every statement.
So How would i Make it into a hex code then merge with texture pack?
Do not use anything from maxmvdw
Why?
yup thats been it
Are you trying to limit the map then? Cause why not just set it to final if it's going to be loaded at startup anyways?
for context
(Debugs didn't help)
Inactive, doesn't develop anymore
[17:02:38 ERROR]: Could not pass event InventoryClickEvent to Duels v1.0-SNAPSHOT
java.lang.NullPointerException: Cannot invoke "org.bukkit.inventory.ItemStack.getType()" because the return value of "org.bukkit.event.inventory.InventoryClickEvent.getCurrentItem()" is null
still the same issue
someone help
im using sqlite so that i dont stuff megabytes of inventory information into PDC which is the easier to code but REALLY stupid solution
im trying to avoid it resizing unnessecary
i already got check of getCurrentItem() is null
but issue is i dont know how sql works
Initialize it as final and it can't be resized
Is there a plugin for it that allows me to name items like that?
wtf are you saying
XD
Did you put a check for null cases?
You want a map with exectly 379 elements right?
i mean a final map can still be changed
so im not sure what that guy thinks either
alright heres what final does
fixed. it was pointing to other class im dumb
it says 'object may only be INITIALIZED once'
@tardy delta Collections.unmodifiableList(synapses);
and since a map doesnt reinitialize when methods of it are called
final maps can still be modified
just not remade entirely
Wait really?
I think you'll have to make your own implementation in that case.
well if i set the init capactiry to 379 and the load factor to 1, wont it have enough space for 379 elements and it will resize the moment you add one more?
so how do i do it
iirc yes why
well that should work then
@tardy delta Collections.unmodifiableList(synapses);
Do you need to change the contents?
The load factor won't change that though. The load factor is basically the point at which extra capacity will be added. HashMaps aren't designed to have fixed amounts. So you'll likely have to extend it yourself.
im clearly not understanding what the load factor is then
I might be wrong
The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.
Taken straight from the docs.
how full as in the size?
Yes
It's basically this.
if list size is greater than threshold
increase hashmap capacity
full as in elements it contains versus the buck size (i.e. the elements it supports without resizing)
ah A loadFactor of 1.0f means "don't grow until the HashMap is 100% full
couldnt i use that?
new HashMap<>(379, 1f)?
I'd add one elements on top of that
Yea, but that wouldn't limit it to only 379 elements. It would just have the initial capacity for 379 elements reserved.
You'd still be able to add and remove like normal.
so new HashMap<>(380, 1F)
Okay ! (This is gradle stuff, so if you've never used gradle please pass your way)
So I try to create a "parent module" which will use sub modules (depend on the server version), but I can't compile correctly !
So here's my structure
RisenCore (parent module)
- src (parent src with all the stuff no depend on the child modules)
- build.gradle
- module1
- build.gradle (dependence on parent module)
- module2
- build.gradle (dependence on parent module)
So I want to compile all that stuff in a single jar file.
But when I compile with the jar task from the parent build.gradle it compile only the "parent", I would like to compile the whole stuff
So here's my 3 build.gradle
(parent)
plugins {
id 'java'
}
group 'net.krisp'
version '1.0.0'
repositories {
mavenCentral()
mavenLocal()
}
dependencies {
compileOnly 'org.spigotmc:spigot:1.19.3-R0.1-SNAPSHOT'
}
setLibsDirName("../exports")
module1
plugins {
id 'java'
}
group 'net.krisp'
version '1.0.0'
repositories {
mavenCentral()
mavenLocal()
}
dependencies {
implementation project(path: ':')
compileOnly 'org.spigotmc:spigot:1.8-R0.1-SNAPSHOT'
}
module2
plugins {
id 'java'
}
group 'net.krisp'
version '1.0.0'
repositories {
mavenCentral()
mavenLocal()
}
dependencies {
implementation project(path: ':')
compileOnly 'org.spigotmc:spigot:1.8.3-R0.1-SNAPSHOT'
}
Thanks again for reading 😭
myeah - paste may be premature here
Calm down, don't need paste, It's like 2 line block code
That is also premature deoptimisation here
where did you declare the submodules?
Can you clarify a little more? Is this list supposed to be able to add and remove elements like normal or is it only ever going to hold 379 elements and do nothing else?
settings.gradle
Or are the submodules more or less independent of each other?
That sounds right
submodules don't depend from each other, they only depend on the parent module
I believe he said, set the elements and then readonly
Can anyone make a Dynamic rainbow text into a hex code?
the map is supposed to be populated at startup with put method, and it will hold 279 elements (recipes) and will never be mutated after that
he just wants to optimize his map
so ye ig (380, 1) will do the work
Fourteen, make a hasmap, populate it then create another unmodifiable or immutable hashmap with the contents of the first
By making it only hold a given number of elements.
Of course that is not clear but it is ultimately what they want
Mention me when you've responded
Collections#unmodifiableMap is just a wrapper
will that cause any performance issues tho?
ImmutableMap
I am afraid I cannot help beyond that - my experience with gradle is limited
there kinda is but just as a wrapper
oof okay 😭
Collections#unmodifableMap
Collections.unmodifableMap(new HashMap<>(x)) to be more exact
that being said you have a minimal performance overhead from doing so
does it matter?
you
unmodifiablemap just wraps the source map iirc
ah i never use imutable maps
how do I know that Player clicked the result item in Anvil?
nms
I think
Pretty sure most anvil stuff is nms based
