#help-development
1 messages · Page 2216 of 1
best way to write this?
Validate.notNulls smh
never seen it like that. all the tutorials and gradle wiki show without. But I use Maven so...
oh
or just a for loop lol
they have custom repo for maven so for gradle is
repositories
I doubt i even use it
iirc nope
nah i accidentially deleted it
I am new to java and i dont really now how this works
since it sends player info packet
I'm referring to your url =' part. All the examples show url '
its right
ok
Oh allright
yez
Noo its hurts my eyes
yez
I would use a lovevly foreach :D
same
thats a foreach.
Hmn
lombok hihihih
Use arrays.aslist instead
ight
There is not much you can do here. If you wanted to use a functional foreach then you would have to stream them which would be unnecessary overhead.
why?
List.of is less efficient
mk
Because it has to clone the array
yeah alr
yea idk why alot of people are so obsessed with using streams
ive never used a stream idk it looks ehhh
Heyo how would I go about make a Bukkit Runnable that used a random time each time in a range?
public static boolean isNotNull(Object... objects) {
return Arrays.stream(objects).allMatch(Objects::nonNull);
}
oh nice
objects.stream() ?
I mean, they're nice
doesnt exist
and as soon as valhalla is delivered they will be competitive with normal loops
they are. but is it rlly needed for looping over a simple list just to null check?
You would recursively let a runnable reschedule itself with a different time,
¯_(ツ)_/¯
yaeh ive seen it
looks really nice
you've seen it?
the valhalla project
I mean not everything of it is delivered yet
like universal generics is still preview or candidate iirc
but ye
some of it is delivered
BuildTools doesnt work. It says starting process for building spigot but it doesnt do anything else. And if i try to close it it tells process x is running do you want to cancel it
Loading BuildTools version: git-BuildTools-1fbeb7f-147 (#147)
Java Version: Java 17
Current Path: C:\Users\toron\OneDrive\Desktop\buildpath\.
Please do not run BuildTools in a Dropbox, OneDrive, or similar. You can always copy the completed jars there later.
This happens when i load build tools it doesnt open a consol it just gives me a file
Why does no one read?
well what does it say....
Same to me
?
Please do not run BuildTools in a Dropbox, OneDrive, or similar. You can always copy the completed jars there later.
I created a new folder for it
but
so?
that isnt a dropbox OneDrive
its stilll in there
Your desktop is inside OneDrive
oh
^
Put your folder somewhere else
for example add it to dokumets=
@ivory sleet whats the difference between your
return Arrays.stream(objects).allMatch(Objects::nonNull);```
and
```java
return !Arrays.stream(objects).anyMatch(Objects::isNull);```
just an idea since it might be faster to finish at one null
! will negate
instead of check them all
yeah thats the pooint
my brain isnt braining
one sec
Are cryptos allow on spigot? Not mining
@AllArgsConstructor
public class SelfRepeatingRandomTimeRunnable extends BukkitRunnable {
private final JavaPlugin plugin;
private final Runnable wrappedRunnable;
private final int minTime;
private final int maxTime;
@Override
public void run() {
wrappedRunnable.run();
int delay = ThreadLocalRandom.current().nextInt(minTime, maxTime);
new SelfRepeatingRandomTimeRunnable(plugin, wrappedRunnable, minTime, maxTime).runTaskLater(plugin, delay);
}
}
ok nvm yeah my question still works
Define cryptos.
like im thinking an idea for the future creating a plugin that represent crypto but for minecraft
Basically mc player mining but fake crypto
Do i explain?
something similar to this? https://www.spigotmc.org/resources/stock-market-plugin-1-8-1-18.54564/
better to use ```java
return Arrays.stream(objects).noneMatch(Objects::isNull);``` for the second one i think
Hi! Should I create a separated class for my every custom inventory, or can I create only one and add all the events there?
I'm pretty new to spigot and just made my first plugin which changes the join and quit message for players. I'm now wondering if there is a way to remove the color prefix from the message in the console. I don't want my logs to be in color or anything. What I want is that the console logs,
[22:03:35] [Server thread/INFO]: swamp4frog has left.
instead of
[22:03:35] [Server thread/INFO]: §eswamp4frog§r has left.
Yeah
coc
My goal is to add a think that x time mines x amount of an int a crypto
I think this already exists
Well as long as it isn’t real crypto mining, you should be fine.
It doesnt touch real cryptos
return Arrays.stream(objects).allMatch(Objects::nonNull);
return Arrays.stream(objects).noneMatch(Objects::isNull);```
whats the difference
Personal preference. It’s up to you how you want to manage your code.
none
ok
OHH!! Thanksss!
PreparedStatement ps = plugin.getMySQL().getConnection().prepareStatement("INSERT IGNORE INFO agencies " + "(ID,AgencyName,AgencyOwner,Balance,MaxBalance) VALUES (NULL,?,?,?,?)");
Seems not valid wtf hmhm
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'agencies (ID,AgencyName,AgencyOwner,Balance,MaxBalance) VALUES (NULL,'Microsoft...'
an AgnecyName that starts Microsoft ?
If you have Intellij then just connect it with your DB. It has auto completion, syntax highlighting and it can find errors in your statements.
Did u mean to do insert info or into?
r u kidding?
wow thanks
does that require ultimate?
Uhm... maybe
😦
not sure. But if you are a student (school or university, doesnt matter) then you get it for free
F
and its way too expensive imo for someone just hobbying
for companies. sure i can understand the price
hey uh
theres nothing in this file
and theres no error message
what do i do with it
its like 150 euros a year
Its 12$ per month. Not too bad.
in Italy the most they give us is the problematic electronic register developed by a pokemon
Why still Command#getName()?
actually i was looking at the organization pricing
its not that bad. but idk if im willing to pay that just to have sql support
How would I make args[0] from commandclass usable in a Listener class
is there anything else usefull?
i need a lil hepl with the sqlite and mysql part of that
anyway... Do you have any idea?
I use quite a few features now. But for onw feature it isnt worth it.
I can help u
What do you need
did you fix INFO to INTO?
LightFurry i can help you, what the issue?
its already written but im not sure why the file is red
is that github
or an error
You are asking why the file is in red?
yes
But hy you care if it works?
How would I make args[0] from commandclass usable in a Listener class
as in
i think theres like
autocomplete for the syntax
if i connect to the database
but i cant see any database thing anywhere
is there way to auto import in intellij?
Arguments of methods only live within the method. When its done, the whole scope gets cleaned up until the next call.
do i need to put the database.db in the resources folder before testing connection?
I'm making a target plugin where you do /target [player]. Opens a GUI which inside you can use different InventoryClicks to effect the targetted player
and will just database.db work in the name field
because you put something that looks like a path
There are hundreds of ways of approaching this. Just use an object oriented approach. Very basic Java.
The most trivial i can come up with is a
Map<Inventory, Player> inventoryTargetMap
i have a question
Yes its done naturally. Never had to import a single type by hand...
uh
If i type fast it asks me to import later
@eternal oxide Workz!!! Thanks bro, you made my day 🙂
how do i setup a region to spawn mobs
Define what you mean by "setup" and "region"
I wouldnt know how to implement this
I would use a BoundingBox with a task that spawns mobs inside.
how can I turn Bukkit.getOnlinePlayers() into List<Player>?
is this valid? Bukkit.getOnlinePlayers().stream().map(Player::getPlayer).collect(Collectors.toList());
Maybe learn java first..
Then you need to learn the basics of java. Only takes 3 weeks. 2 if you are passionate.
Stream#anyMatch return a booleans right?
yes
i mean i just need to create an area that i can spawn mobs in using my already writen cod i can send screen shots if needed
iirc it actually returns a List<Player> already (which is shadowed by a Collection). Just cast it and see what happens.
it returns Collection<? extends Player>
List<CraftPlayer> iirc
im not sure if cast works
aight ive done this, how do i view the database? i dont see any of the columns i added showing up
Question is: Why do you need a List?
i mean i just need to create an area that i can spawn mobs in using my already writen can i can send screen shots if needed
bc of a different method
its grey
List<Player> playersAvaible = new ArrayList<>();
for (Player player : Bukkit.getOnlinePlayers()) {
playersAvaible.add(player);
}```
i cant click that though
List
This looks like an addAll with extra steps
probably wanna set initial capacity
Why would that effect anything?
idk where my getOnlinePlayers comes from but its interesting
Also ArrayList has a bulk constructor.
public List<Player> getOnlinePlayerList() {
return new ArrayList<>(Bukkit.getOnlinePlayers());
}
ok fam
👍
i mean i just need to create an area that i can spawn mobs in using my already writen cod i can send screen shots if needed
I would define the area on a lower level (architectural wise) as a BoundingBox. Getting a random Vector inside should be pretty easy.
So just do that and then let a scheduler spawn mobs there.
i already have a random vector so makes it easier
whats the best way to get all players with a certain attribute? like if theyre in creative mode, they have a permission, theyre in the nether, etc
is there an easy syntax for it or do i just for loop it
well not easy syntax,. but efficient
if you want to do it based on all kinds of different attributes
2 ways:
- Track them when states change.
- Iterate over them and filter
public static Collection<? extends Player> getWorldPlayers(World world) {
List<Player> players = new ArrayList<>();
for (Player player : BukkitUtils.getOnlinePlayers()) {
if (Objects.equals(player.getWorld(), world)) {
players.add(player);
}
}
return players;
}```
something better than this
you could make a method that tests using a predicate
How do i give a play a water bottle? all drinkable items fall under the item "potion"
yea not too sure about predicate
because?
wait let me show u
For the iterative approach:
// Abstraction
public List<? extends Player> getAllPlayersWhere(Predicate<Player> filter) {
return Bukkit.getOnlinePlayers().stream().filter(filter).toList();
}
// Example implementations
public List<? extends Player> getAllCreativePlayers() {
return getAllPlayersWhere(player -> player.getGameMode() == GameMode.CREATIVE);
}
public List<? extends Player> getAllLowHealthPlayer() {
return getAllPlayersWhere(player -> player.getHealth() < 5);
}
?
public void test()
{
getPlayers((player) ->
{
return player.getGameMode() == GameMode.CREATIVE
});
}
public Set<Player> getPlayers(Predicate<Player> condition)
{
Set<Player> players = new HashSet<>();
for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
if (condition.test(onlinePlayer)) players.add(onlinePlayer);
}
return players;
}
for example
public void spawnMobs(int size, int mobCap, int spawnTime) {
task = new BukkitRunnable() {
@Override
public void run() {
int spawnAmount = (int) (Math.random() * (mobCap + 1)), count = 0;
while(count <= spawnAmount) {
count++;
int ranX = getRandomWithNeg(size), ranZ = getRandomWithNeg(size);
Block block = world.getHighestBlockAt(ranX, ranZ);
Location loc = block.getLocation().clone().add(0, 1, 0);
world.spawnEntity(loc, EntityType.ZOMBIE);
}
}
}.runTaskTimer(this, 0L, spawnTime);
}
@Override
public void onDisable() {
Bukkit.getLogger().info("Plugin Disabled");
}
private int getRandomWithNeg(int size) {
int random = (int) (Math.random() * (size +1));
if (Math.random() > 0.5) random *= -1;
return random;
}
}
ow
wowww
that the code handleing the mob spawning currently
please use ?paste for alot of code
okay soz
0L 😦
so what exactly is the condition?
?paste
gotta go fast
its testing if the players are in gamemode creative
infinitely fast infact
that will now return a Set of only all online players that are in creative mode
the entire Potion class seems to be deprecated...
this is it
okay
Mine is one line so it runs faster 
which method do you think is better?
so how could i implement the BoundingBox into my current code
fine, fine you win
cant argue with that logic
true true
System.exit(1);
how can I use TabCompleter for two args
faster 😄
yesyes
You can check the length oh the args list
First improvement i would apply.
private int getRandomWithNeg(int size) {
int random = (int) (Math.random() * (size +1));
if (Math.random() > 0.5) random *= -1;
return random;
}
to
private int getRandomWithNeg(int size) {
return ThreadLocalRandom.current().nextInt(-size, size + 1);
}
I dont get it, how can I check which argument im at
Now all you need to do is span a BoundingBox and select a random vector withing that box inside your runnable.
nvm
Block block = world.getHighestBlockAt(ranX, ranZ); is returning as null and i cant seem to figure out why
world is probably null
I've already tried waterBottleMeta.setLore(null); but it doesn't work
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
if(command.getName().equalsIgnoreCase("yourcommand"){
if(args.length == 1)
return Arrays.asList("first autocomplete")
else if(args.length == 2)
return Arrays.asList("second autocomplete")
}
}
yea already got it
??? why would that be
String[] words = event.getMessage().split(" ");
for(String word : words) {
for(Player p : Bukkit.getOnlinePlayers()) {
if(p.getName().equals(word)){
p.playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 2, 1);
event.setMessage(event.getMessage().replaceAll(p.getName(), ChatColor.translateAlternateColorCodes('&', "&a&o" + p.getName() + "&r&f")));
}
}
}```
Anybody knows why this doesn't play the the sound to a mentionned player in the chat?
ItemFlag.somethingHidePotionsMetaOrWhatever
There's a fun Vector#getRandom() method too which solves a lot of problems already. Multiply it by a scalar and you're good to go
https://hub.spigotmc.org/javadocs/spigot/org/bukkit/util/Vector.html#getRandom()
declaration: package: org.bukkit.util, class: Vector
Because world is never initialized
Im guessing p.getName() doesnt equal word
Add a sysout before and after the if statement to check
it works when you mention your self tho
lemme check
maybe you should use equlsignorecase ?
Ah yeah. But this will only work if the BoundingBox is a cube.
is there a lower and upper bound to AbstractHorse#getJumpStrength()
You should use Bukkit.getPlayer(String) instead
or can i have spaceship horse with 1000 block jump height
Try it out and tell us
me?
Yes
as far as i know it will always be a player
I have yet to find an occasion where a mere HumanEntity clicks an Inventory...
how do i do?
Fine i guess? Thats a random question...
Just blindly cast it. And tell no one i said that.
I'm getting a regression between my tests with mc 1.17.1-1.18.2 and 1.19 with my HeadSweeper plugin. It works fine in 1.18.2 and earlier, but when using spigot or paper 1.19 the head seems to lose its nbt data and just becomes a steve head. This only happens when the head is left-clicked, not when it is right-clicked. Attached is the piece of code that should cancel the player interact event. Any idea why this could be happening? Is this a client-side or a server-side issue?
Just ask the one who clicked politely. In most cases they will just tell you if they are a player or not.
Are you sure this is not a rate limiting problem?
what if my housepig clicked it
It happens consistently in 1.19 and never happens in 1.18.2 and earlier. All tested servers are using Java 17. They are run from the same pc and on the same port (not at the same time).
Put a wig on it and treat it as the average 1.8 player.
whats the "heart beating" sound effect that hypixel uses in murder mystery assassin mode
modern slavery, i like
btw why do you use metadata?
I have a problem with my InventoryClickEvent where it is only being registered when I click on an item out of an inventory. I'm trying to detect when a player places an item into a gui instead
Plugin was originally created for 1.7.x 😄
oof
But I think the metadata isnt the issue, because the other code afterwards does run.
Can you check with a second client if the head changes for them if the initial player clicks it? Then we can tell if its client or server side.
Good idea. I'll get a friend to join and check
Dont check for the clicked inventory but the primary inventory involved in the event.
i dont understand why i wouldnt be initialised becasue i have a line in onEnable saying Bukkit.getWorld("world");
and a line establashing world and a World
Im guessing you are doing something like this in your main class:
private final World world = Bukkit.getWorld("world");
But this code is being run way before any worlds exist.
You need to run your code in your onEnable:
public void onEnable() {
this.world = Bukkit.getWorlds().get(0);
}
Thacks for the help!!
I'm using e.getInventory
If I use the actual inventory
it dont work
Hey
I have an existing plugin what uses gradle, but I cant import spigot library into the project, can anyone help me? 🙂
pretty sure
How do you add spigot as a dependency?
declaration: package: org.bukkit.event.inventory, class: InventoryClickEvent
I can handle that, I just need the gradle thing
I've never used gradle
idk why, my code is not working can someone help me https://pastebin.com/41yWJ2jm
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Well... Just make sure that your never add spigot (or any library for that matter) manually to your project and always use the dependency manager for it.
Then you should be fine.
?notworking
"Does not working" is a useless statement. Please describe what exactly is not working, what you expect it to do, and what actually happens. If you get any console errors, also ?paste the entire stacktrace.
it does not change the game mode to creative
Is there an error in console?
?paste
no
nothing happens?
how can i use pterodactyl's api in a spigot plugin
nothing happens
First of all: The reformatting
https://paste.md-5.net/jahotidoki.java
Have you registered it in your main and plugin yml?
more of a Java question, but
private static <E extends Enum<E>> E getRandom() {
Random random = new Random();
return E.values()[random.nextInt(E.values().length)];
}
I'm trying to make this method return a random enum value from a given enum, but I'm getting The method values() is undefined for the type E. What's the correct way to do this?
First off, this is a CommandExecutor so it must be registered. In which case you don;t need to check the label nor the permission. set the permission for the command in your plugin.yml
I did this
getCommand("gmc").setExecutor(new Creative());
getCommand("gms").setExecutor(new Survival());
getCommand("gmsp").setExecutor(new Spectator());
wait, I need to set the permission in the plugin.yml
vault is a dependency in my plugin and i have
private boolean setupEconomy() { if (getServer().getPluginManager().getPlugin("Vault") == null) { return false; } RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class); if (rsp == null) { return false; } econ = rsp.getProvider(); return true; } public static Economy getEconomy() { return econ; }
whjcih is called when my plugin is enabled but whenever i use getEconomy() its always null, why is this happening? vault is on my server, its a dependency, so this makes no sense
- Vault```
you are probably storing your economy reference before vault/the eco plugin has started
do i need to put the permission in the plugin.yml
Do you even have an eco plugin?
You need more runtime context. E is erased.
yes
each command has its own permision
permission: plugin.gmc
wdym
do i take in the enum class as a parameter instead?
Like this for example:
private static <E extends Enum<E>> E getRandom(Class<E> enumClass) {
Random random = ThreadLocalRandom.current();
E[] constants = enumClass.getEnumConstants();
return constants[random.nextInt(constants.length)];
}
i did not know getEnumConstants was a thing
thanks
debug some of those return false in the setupEconomy. See where its failing
add some sysouts to see how far its getting
Do you depend on Vault in your plugin.yml?
yes
Your plugin would not start if Vault didn;t exist as its a depend
So I've read it. What am I exactly looking for. Sorry for being such an idiot.
I didnt even fully understand your problem.
You want to check for clicks in the bottom inventory if the top inventory is one of your custom ones?
When do you call setupEconomy?
Ah no. So I have a gui. And I'm placing an item into it. I'm trying to detect it but the event only triggers when I take the item out of the gui
Try to also use InventoryDragEvent?
if(event.getClicked is your custom inv) <- Only true if you click the top inv
instead of
if(event.getInv is your custom inv) <- true if you click anywhere while your top inv is the custom one
We found out that this is a client side issue.
Not reading that...
Hi ya'll, I'm new to spigot and I'm trying to learn about good conventions for putting a cooldown on handling events.
For example, lets say we wanted to message a player the block that they're standing on every 1 second whenever they move,
I'm trying to find a good standard to practice this since most events are not handled every single tick.
Here is some java/pseudocode for the ideas
// approach 1: check every tick for player move event and only issue message after 1 second
// this feels kind of inefficient because you have to listen for every single PlayerMoveEvent, but maybe its the standard?
// we can also clean this up and handle this as a new event
@EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
// keep track of time in map somewhere
int ticks = SomeTimeKeepingMap();
if (ticks % 20 == 0) {
player.message("you are standing on this block %s");
}
}
// approach 2: issue a BukkitRunnable task to manually check PlayerMoveEvent every 20 seconds (not sure how to manually listen though)
// sucky because infinite loop but more efficient than the first
// also sucky because this seems like spaghetti code and not a correct approach for the problem
public class MessagePlayerAboutBlockBelowTask extends BukkitRunnable {
private final JavaPlugin plugin;
private int counter;
@Override
public void run() {
// check event on time
if (counter % 20 && plugin.listenForPlayerMoveEvent()) {
player.message("you are standing on this block %s");
}
}
}
// and then later start this task on plugin enable
// approach 3: this was my first intuitive approach
// I truly don't believe this is possible but maybe I'm missing something that makes this a standard convention
// Listener.java
@EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
// run task that constantly checks every second and cancels when no more player movement
BukkitTask task = new MessagePlayerAboutBlockBelowTask(plugin).runTask(plugin);
// make listener synchronously wait for task to finish (I don't think this method exists anywhere)
this.waitForTaskToFinish(task);
}
Tricky. There are several ways of handling that.
Async board update?
so its just the first part of the code. The if (e.getview etc) You can ignore the NBT and item data etc and the rest after that
what's an async board update?
any1 know?
Headsweeper is minesweeper using heads in minecraft. I meant in response to 7smile7 as solution for my problem
where I update the minesweeper board asynchronously.
that's a pretty cool concept o:
Here is the problem of #1 (and #3)
If the player stands still on a block without moving then he will never be notified.
The example I put is not the best use case, but I am specifically wondering about how we can put cooldowns on listening to events. I specifically tweaked the problem to "whenever the player moves". That's my bad though
But yeah in that case if we just want every 1 second regardless of player movement, we would just loop through forever with a task I think
this is just generics in java at its finest
so I have this line: private final JSONObject obj = new JSONObject();
and I use obj.remove() and obj.put() and it works fine but no json file is created and idk why
its json-simple
I mean
can you help me a bit? I cant use gradle thats it
you need to write the object through some dumpster
wdym
There are very few circumstances where adding a cooldown on an event makes any sense.
But here is a trivial approach
private static final long MAX_MILLIS = 1000L;
private final Map<UUID, Long> moveEventTimestamps = new HashMap<>();
public void onMove(PlayerMoveEvent event) {
long lastMoved = moveEventTimestamps.computeIfAbsent(event.getPlayer().getUniqueId(), key -> 0L);
if(System.currentTimeMillis() < lastMoved + MAX_MILLIS) {
return;
}
event.getPlayer().sendMessage("You moved.");
}
use JSONParser ytg
Whats wrong with just using Gson (which is already included in Spigot)
The home of Spigot a high performance, no lag customized CraftBukkit Minecraft server API, and BungeeCord, the cloud server proxy.
I see, thank you @lost matrix! This kind of looks like approach #1 that I have. This is really insightful. I didn't think it would be based on uniqueness of users as well.
is there any way that I could generalize this
More context pls. This looks like a design problem. Casting is the only way to infer type arguments here.
Does anyone have any public github repos available of their own plugin projects that you wouldn't mind sharing? I think it would be nice to learn by example 😅
so basically I'm making a skript addon. I have to make an enum so that I can correctly register the persistent data types and allow the users to just type those in (since they're variables in the actual persistentdatatype class)
This is the enum
public enum PersistentDataType{
SHORT(org.bukkit.persistence.PersistentDataType.SHORT),
INTEGER(org.bukkit.persistence.PersistentDataType.INTEGER),
LONG(org.bukkit.persistence.PersistentDataType.LONG),
FLOAT(org.bukkit.persistence.PersistentDataType.FLOAT),
DOUBLE(org.bukkit.persistence.PersistentDataType.DOUBLE),
STRING(org.bukkit.persistence.PersistentDataType.STRING);
/*
Removed the below tags due to issues setting & getting
INTEGER_ARRAY(org.bukkit.persistence.PersistentDataType.INTEGER_ARRAY),
LONG_ARRAY(org.bukkit.persistence.PersistentDataType.LONG_ARRAY);*/
private final org.bukkit.persistence.PersistentDataType<?, ?> type;
<Z, T> PersistentDataType(org.bukkit.persistence.PersistentDataType<T, Z> type){
this.type = type;
}
public org.bukkit.persistence.PersistentDataType<?, ?> getType() {
return type;
}
}
since Which spigot API version CustomModelData, in ItemMeta class has been implemented?
and I don't want to have to switch each and every one of those to supply the type in the PersistentDataContainer#set() method, the whole reason of why I'm trying to save the var in each enum value
@SuppressWarnings("unchecked")
public void apply(PersistentDataContainer container, PersistentDataType<?, ?> type, NamespacedKey key, Object value) {
container.set(key, (PersistentDataType<?, Object>) type, value);
}
*Not sure if this works
I ran into the same problem again, the config is not saving its comments
1.16 i believe
I remeber it was 1.14 but I am not sure
might as well be
so it was in 1.13
it says fileNotFound
JSONParser parser = new JSONParser();
try (Reader reader = new FileReader("src/main/resources/data.json")) {
JSONObject jsonObject = (JSONObject) parser.parse(reader);
jsonObject.put(location,amplifier);
} catch (IOException | ParseException e) {
throw new RuntimeException(e);
}
}```
but it's here
your file is not in src/main/resources/data.json
it's in /data.json
also I doubt that you can just use a FileReader to read a resource
it still doesn't find it
as I said, you cannot just use a FileReader because you don't have any file at that path
you only have a resource in your .jar
so you do plugin.getResource or plugin.saveResource as fourteen said
where else would it be? o0
I was told that it must be there
yea it has to be there
wait so what about the fileNotFound problem?
I told you thrice. use getResource
everything in "resources" gets put into the root "folder" of your .jar
whether it ends up in your plugins data folder depends whether you tell your plugin save it there
try (Reader reader = new FileReader(plugin.getResource("data.json"))) {
Cannot resolve constructor 'FileReader(InputStream)'
Yes, you cannot use a FileReader without a File
use an InputStreamReader
what
you save it to file of course
JavaPlugin#saveResource("/config.yml") for example takes the config.yml out of the .jar and saves it
in the data folder
what are you even trying to do?
what do you need data.json for?
you can easily save included files with saveResource()
save location as key and integer as value like in hashmap but i want it to be saved after restart and reload so i want to use json
how would you have done this?
but why do you have a json file included in your .jar?
shouldn't it be there?
no, why?
whereelse it would be saved if not in there
in the plugin's data folder
like in /plugins/ChestSort but definitely not inside the .jar itsef lol
i don't see any data folder in the project
of course not. the data folder is on the server
plugins/ChestSort/...
that's the data folder
ok
it's where an admin expects to find the config.yml file
there you can save your json file
File myJson = new File(plugin.getDataFolder(), "myJson.json");
plugin#saveResource -> will save the provided file from the resources folder to the datafolder of the plugin, so /server/plugins/<your plugin>
does anyone know a good server host that is pretty cheap and has good performance
Minejut
and if (!myJson.exists()) plugin.saveResource("myjson.json");
Variable 'plugin' might not have been initialized
?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.
I don't like minehut
"plugin" is of course a reference to your plugin's instance
well
for example "this" in your main class
I have already had an instance before for the config
yeah then use that
public newLimit(JavaPlugin plugin) {
this.plugin = plugin;
}```
newLimit is the class name
i get this
?di to get the plugin
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
mwh ye you already got it
is 1.19 having problems with saving comments in config or wtf is going on
and name your class names with an uppercase letter
did you enable that?
enable what?
can you send me a basic example plugin because i actually don't understand what to do?
i'll understand if not
parsing comments
MemoryConfiguration.options().parseComments(true);
no I just use saveDefaultConfig() in the onEnable
saveDefaultConfig() will save the comments.
as I thought parseComments is true by default
saveDefaultConfig() simply saves the file exactly as it is
I highly suspect that you save the file manually again later instead of only calling saveDefaultConfig
I have to check that but I can't remember touching it again after loading it
is this the result of doing NOTHING besides calling "saveDefaultConfig()"?
first time using mysql but whenever i join the server i get this error and my data is not saved anyone know what this means
if they need any files just let me know
https://paste.md-5.net/dapeyenaho.sql
your SQL statement is incorrect
do you know what line
what's the SQL statement in CustomPlayer line 44?
statement1.executeUpdate();
yeah but what's the statement
No the statement
PreparedStatement statement1 = plugin.getDatabase().getConnection().prepareStatement("INSERT INTO players (ID, NAME, UUID, balance, minecoins, crystals) VALUES (" +
"default," +
"'"+Bukkit.getPlayer(uuid).getName()+"'" +
"'"+uuid.toString()+"'" +
0 +
0 +
0 + ");" );
use code blocks pls
yes, I restarted the server now and tried it again and now it's parsing the comments too
?paste it atleast
Why are u using prepared statements without ?s
I have started a raid and waited for the pillagers to win and they killed all the villagers but the raid hasn't been finished.
i've been waiting for half an hour after the villagers were dead and nothing happens.
any ideas?
that definitely does not look correct. Print out the whole statement before executing it. For example why are you adding 0 + 0 + 0? And why are you using PreparedStatements and still manually insert the values?
doesn't a player have to be there somehow and get killed or sth?
you're supposed to lose if all the villagers in a raid are dead
didnt know. no idea then
your SQL statement should look like this:
im new but ive watched some videos on it are u able to alert me to my mistake
PreparedStatement statement = ...prepareStatement("INSERT INTO players (ID, NAME, UUID, BALANCE, MINECOINS, CRYSTALS) VALUES (?, ?, ?, ?, ?, ?)");
statement.setInt(1, someId);
statement.setString(2, someName);
....
https://www.baeldung.com/java-statement-preparedstatement read this please. the COMPLETE thing please, not just the beginning. Because the beginning is about "what NOT to do"
can someone explain the difference between String.valueOf and .toString()
they seem to do the same thing after testig
null safety
this look better?
yes, that looks way better! and this could even possibly work. except that you used 5 for crystals. should be 6
toString will throw npe right if null
valueOf is null safe
but valueof will return 'null'
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}```
someObj.toString() = NPE if someObj is null
this does?
String.valueOf(someObj) is "null" if someObj is null
that's the source code of String.valueOf
on column 1 it is a ID value how do i get mysql to just iterate it for me
is the ID column set to AUTO_INCREMENT in your sql table?
yes
okay then simply do not provide the ID in your statement
one sec
here - you simply do not tell it about ID and then mysql will use the default value which in this is the auto incremented value
ahh ok yes ty
How do I keep the comments when changing a value in the config?
yourConfig.options().parseComments(true)
like, let's say I do getConfig().set("SomeValue", true);
after that I would have to use saveConfig() ?
I think so
but saveConfig() removes the comments
even when you set parseComments(true) ?
yeah of course - substr
if(myString.length() > 1024) {
myString = myString.substring(0,1024);
}
I normally put that into a method if I need it more than once
public static String subStringIfTooLong(String string, int length) {
if(string.length() <= length) return string;
return string.substring(0,length);
}```
yep still removing the comments when I use saveConfig()
but how else would I save the config after I changed a value in it?
Sorry for this being a simple question, I’m just unable to find the answer online.
Would ProxyServer#getPlayer(uuid)#getName() be able to return the uuid of a player that has joined the bungee network but is currently offline?
Can I make a new thread and run bukkit schedulers on it?
No. Bungeecord is a Proxy that handles live connections. No offline data is stored there.
Are those two independent questions?
on the new thread..
Thanks for helping
So first of all: You cant run a scheduler. A scheduler schedules tasks.
Im not entirely sure what you are asking. But the BukkitScheduler is thread safe which means you can schedule runnables
from within another thread context.
how do i get the default no permission message
I want to get a command's no permission message, but if it doesn't exist, then get the actual server default message, ("I'm sorry, but you do not have permission...")
So this
new Thread(() -> Bukkit.getScheduler().runTask(SpigotSandbox.this, () -> System.out.println("Hi"))).start();
Or this
CompletableFuture.runAsync(() -> Bukkit.getScheduler().runTask(SpigotSandbox.this, () -> System.out.println("Hi")));
Or this
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(() -> Bukkit.getScheduler().runTask(SpigotSandbox.this, () -> System.out.println("Hi")));
Is completely safe.
What happened to Particle.BARRIER after 1.16?
Bad news. I've done some digging and it seems like this message is hard coded.
damn
Well not so bad after all because you can just create a constant
ChatColor.RED + "I'm sorry, but you do not have permission to perform this command. Please contact the server administrators if you believe that this is a mistake."
And send it instead.
Honestly this should be in the spigot.yml
it should
Is there an event that gets called when a gravel/sand/dragon egg block is destroyed by a torch?
Never mind, found it
EntityDeathEvent
ok thanks!
The entity type is FallingBlock
Hey, I am trying to prevent players from using commands while in an active arena match in my PvP plugin. It seems to me that cancelling the command in the PlayerCommandPreprocessEvent is the best solution, however I can not get this event to trigger what so ever. Any ideas as to why it won't run?
Forgot to register the listener?
getServer().getPluginManager().registerEvents(new Main(), this);
That should do it, in the onEnable(). Right?
Is Main your JavaPlugin class?
Yup. Can I not do EventHandling in the JavaPlugin class?
naming main class main 
Then your plugin will just crash and not even load.
You can but I would use this instead of new Main()
^
Hm, odd. It runs fine, but that explains why the listener ain't working haha. I'll try separating them. Thanks 🙂
Replacing new Main() with "this" fixed it actually. But would it be beneficial for me to separating anyways?
Yes. There is a code principle called "single responsibility". Which boils down to: A class should only have one single purpose and nothing else.
Separation of concerns is another one that tells you to... separate your concerns. Its more abstract but still applies.
Aha, makes sense! I'll make a separate class for listeners then. Thanks for clearing things up for me guys, very new to spigot development so forums like these are invaluable 🙂
?paste
Does not give console error but the command does not work. I really dont know what it is
Is the command in your plugin.yml?
Yes sir
name: TargetGUI
version: '${project.version}'
main: com.william.targetgui.Main
api-version: 1.19
commands:
target:
now it gives out a error though
For one thing you need a return in the command when you check if the sender is a player
the command should be /target [player]
You’re going to want to return true if the command succeeded, not false
The target player should not be static
Im trying to compile smth for a friend but intellij complain saying: "cannot access net.grandtheftmc.gliders.listeners" when the packet is there
how else would I use it in another class
need it for Listener...
You’re going to need to pass it around
What could be?
If two people run the command that’s going to overwrite one of them
How would I go on about fixing that?
It seems like you don’t know Java very well, I would recommend learning the language better before attempting to make a plugin
Is there some issue with enchanted items in crafting recipes?
Other than the table not forcing you to match them exactly
Any dude?
This was working the other day and now it just isn't working
EntityDeathEvent doesn't seem to work, it only works for a LivingEntity
?
Have you tried without enchantments to confirm that’s the issue?
Forgot to add this to that message, there's another recipe that's eight enchanted items and one normal item, it works
With both I'm checking to make sure that the items provided have the custom name and enchantment for the glow
It works with the 1.16 API, there's no difference in the recipes
There’s no event for what you want
public static ShapedRecipe soulVialRecipe() {
RecipeChoice.ExactChoice sgRC = new RecipeChoice.ExactChoice(soulGlass());
RecipeChoice.ExactChoice soulariumRC = new RecipeChoice.ExactChoice(soularium());
NamespacedKey svKey = new NamespacedKey(plugin, "empty_soul_vial");
ShapedRecipe svRecipe = new ShapedRecipe(svKey, emptySoulVial());
svRecipe.shape(" S ", "G G", " G ");
svRecipe.setIngredient('S', soulariumRC);
svRecipe.setIngredient('G', sgRC);
return svRecipe;
}
There's the recipe for what isn't crafting
The recipes for the other two items it uses are working
Let’s see the working ones
oh, wait
Lol
how the hell did I not notice that
Ding
if (!inventory.getResult().isSimilar(emptySoulVial()) && inventory.contains(soularium(), 1)) {
inventory.setResult(new ItemStack(Material.AIR));
} else if (inventory.getResult().isSimilar(emptySoulVial()) && (!inventory.contains(soulGlass(), 3)
|| !inventory.contains(soularium(), 1))) {
inventory.setResult(new ItemStack(Material.AIR));
🤦♂️
That’ll do it
Now I wonder if the issue with the drop event is caused by something stupid like that, too
You should identify custom items by tags in their PersistentDataContainer
as in add a custom tag to the items?
Is it possible to find when the ender dragon egg breaks then?
Hm. Paper has a "EntityRemoveFromWorldEvent" which is launched for sure.
Try checking out if the EntityDropItemEvent is called.
How do you clear advancements from a player?
how would I stop players from opening any chest ?
in the InteractEvent check if its a Chest and cancel the event
1.8*
Still the same
I made a custom snowball with PersistentDataContainer, when I throw the snoball does it keep it's PDC???
no, you have to apply it to the projectile
ohhh
Can I spawn a projectile with custom texture???
yes
how???
As in I should add a custom tag to identify the item?
https://paste.md-5.net/ozahetilor.java This is an Example of Launching snowballs with different items.
It puts MetaData on the Snowball, but you can use PDC too
It allows you to throw spawn eggs instead of having to place them
https://paste.md-5.net/adewazuref.cs I want to add this to snowball meta.setCustomModelData(0000);
if you are using custom model data then get teh meta and set it. Don;t forget to put the meta back on the snowball
And how am I supposed to do this???
EntityDropItemEvent worked. Thank you!
How do I check whether the ender dragon egg has been broken by a piston?
Can someone explains me what is the purpose of Maven/Gradle? Cause I can't figure it out myself, it's like doing everything I've done so far but everytime I need to add a dependency I have to copy paste some stuff in pom.xml
So I'm making a /target <player> plugin. When you do /target <player> and he is online you get a GUI which you can use to effect the specified player. For example click in the inventory to kill. But it seems like I cant figure out how to store the args[0] as a UUID for my Listener class. Since when I use the GUI it should execute it
I dont know if that made any sense but
It made
I 've made sth similar
Maven/Gradle is a dependency manager. It handles all teh resources your project needs, builds shades and packages your jar
So do you know what I should do?
I can also send the classes if needed'
Is it possible to convert BlockData to MaterialData or the other way around?
No they are different things
So for instance I want to had a dependency to my plugin, I just need to copy past the given code in pom.xml? And that's it?
However MaterialData is depreciated so you should not be using it
yes
I want to know how I can use or store the target in my Listener calls
And what should I do if it doesn't find the dependency xD?
class
make sure you have the right repository included in your pom
So could you explain the problem again???
I need to know how I can use the target in my Listener calls. To do target.setHealth(0); etc.
ohhhh
I just have to copy <dependency> ... <\dependency> into <dependencies>...<\dependencies> and same thing for repository, right?
That's not very helpful. Especially in a community where we are all here to learn and teach each other.
Some dependencies are in different repositories, so you have to have both
@untold jewel can you send your class and tell me what the exact issue is?
I can, thank you
So when I do /target [player] and the player is online it opens a GUI which I can then use to "punish" the target with. So if I click a block inside the GUI it kills the targeted player
But I cant access args[0] or target from my listeners class
and I dont know how I can store the target or use it
Args 0 is the player
So the method u use to open the gui
It should open it for the player
Thank you
But also let that method takenthe target as well
I cant click your listener class btw
I just want to know how I can access target from my listeners class
U need to have a map somewhere
Player target = event.get.... etc
I have target = bukkkit.getPlayerExact(args[0]) but in listeners I want to use target.setHealth(0)
Maybe in ur main class
yes
So map<uuid, uuid>
First uuid is of the sender, second is target
When they run tje command, put them in this map
When they close tje inv remove them
The*
The same way u put targetgui in the constructor, u can put targetmap
Wait so I have a question about your plugin design, how come you're listening for an inventory click event?
It's for a gui
I am opening the GUI which im going to punish the target wtih
so when I click a block inside the GUI it kills the targeted player
Ohhhhhh I see.
and you want that instance of the target to be in your listener class?
Is that what you're asking?
Yes so I can use target.something
I know maybe these questions are extremly noobie but I appreciate the help !
Oblak
i am having problems with bungee and connecting it is telling me SEVERE in everyone and it will not let me do the server command to all of the servers
Create a map in ur main class
okay..
And pass that map to ur listener and command
you don;t need a map, just pass the variables
I dont know how his plugin layout looks
how would I do that
Make a static variable for your class, then make a getter for that variable in that class
then in your other class use ClassName.get();
that's how you could access something from another class
But this is much easier if you just do this all with a listening I don't understand why you need a command
I recommend rewriting the plugin
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) return;
Player target = Bukkit.getPlayerExact(arg[0]);
if (target != null) new PunishGUI((Player)sender, target);```
You could do something like a punish command that gives you an item and when you click that item it opens up a GUI that you can interact with
this eliminates the need to share any variables
create a PunishGUI class with a constructor which accepts those values
Have to say I'm a little confused but I'll give it a go
as you are talking about args I assume you start with a command to open your GUI
The correct way to do it is what he said, but if you're not there yet, just try what I told you
Have a command that gives you a specific "punish" item
then do everything in the listener
That's what I recommended before as well
yep
Idk I'm just trying to give him options
i am having problems with bungee and connecting it is telling me SEVERE in everyone and it will not let me do the server command to all of the servers
If he has an "admin" type item in game he has to do all sorts of crap to ensure it doesn't end up in a players hands
ElgarL do you want my InventoryManager class too?
I'm not writing it for you 🙂
just implement that code I showed you into your existing command
for a start
your IDE will even tell you there is no PunishGUI class and give you an option to create one
I have a targetGUI class
ignore that for now
in your GUI just make a constructor and initialize your field variables to whatever is fed into the constructor
I want you to use the IDE suggestion to create a Punish class as it will also create teh constructor for you
man im at a loss for how to figure out the next exit a minecart will take on a corner
so i have the actual momentum vector
i have the position along either X or Z
i have the pair of exits (relative to the rail it's on)
but i can't figure out how to use these things together to work it out, i keep getting stuck in the same loop
- need the exit to figure out if it's past the midpoint (flips velocity)
- need to know if it's past the midpoint to figure out the exit
the problem that keeps complicating it is the momentum vector could be just wrong if the player holds a sideways key it'll add momentum that way
get the Direction of the minecart not the velocity
wait
the actual rotation right
Ya hmmmmmmmmmmmmm
Thanks i think that could be what i need to work it out
just spent 3hrs staring blankly at it waiting for an idea lmao
Thansks for the help but it really does not seem to compute
?paste ok show me your command class
Listener: https://paste.md-5.net/uxeyakural.java
Command: https://paste.md-5.net/icepozutuv.java
InventoryManager: https://paste.md-5.net/ojidemiluk.java
targetGUI: https://paste.md-5.net/bohojekexu.java
ok scrap your Listener class....
throw it out the window
You need a class that handles your GUI, it will have its own Listener, so you'll be combining your targetGUI and your listener class
however, this needs to be useablke by more than one admin so you need to instance your targetGUI class
um, your code seems super over the top complex
ok let me throw an example together
Is there a way to clone an Entity?
Like have a major Entity (or its data) and use its information to create a new minor Entity?
You can achieve that by using NMS. Clone the NBT tag and create a new Entity then load the NBT tag with the new one.
Spigot as an API has a level of prerequisite Java knowledge you can’t function without. I’m happy to help someone with issues or confusions they have about the api or minecraft, but they need to invest some time in learning the language first
Oh, I don't mean NBT or something like, I mean EVERYTHING, like Health, Passengers, Inventory, Metadata etc
Thats all serialized into an NBT component (except the passenger)
start a thread
Thread
How do you prevent a player from giving the allay a certain item? I tried PlayerInteractEntityEvent but it didnt work
InventoryDragEvent
prevent teh player dropping the item
you have to right-click to give an item to an allay, not drop it, right?
using optifine, it's possible to have multiple variations for the same color or style with a resource pack. Would it be possible to choose which one of these variations is used server-side?
for example the horse color "chestnut" has 5 different colors that are randomly picked from the resource pack, and the horse style "black" has another 7 different variations
i want to choose which variation to use
idk if this is possible though
because on a server restart the variations randomize again
(ping me if you respond pls)
Cannot determine path to 'tools.jar' library for 17 (C:\Program Files\Java\jdk-17.0.3.1)
wat
is my intellij outdated or something
I don’t believe this is currently possible if Optifine is the one responsible for the variations. If the resource pack is handling things and has variations included, you could manually set which one you want by assigning custom data. However it would have to be an explicit call.
Yea the thing is it’s not custom model data, optifine randomly chooses a new variation on its own
I was just wondering if there was some kind of "Optifine resource pack" plugin that let me control it
Because what’s also interesting is that the same mob looks exactly the same on two different clients
Unfortunately, I think that there would have to be an optifine setting added for controlling variations. I think I tried to do something similar and found that optifine just does variations with no way to control it by default.
I’m not an expert on resource packs, but I do know that controlling variation is possible with custom data and if the pack is the one handling the textures, it should work just fine even for optifine players.
I know that you can do some things with a resource pack that would only work for players who have optifine installed. (Custom enchantment book tier textures is one example)
@ornate patio
why doesnt extend javaplugin work now :/
Cause you're missing the dependency
i added the jarfile as a library
Use a package manager like maven
maven has all those weird parameters for adding dependencies
?bootstrap
Bootstrap Jar
The main spigot-1.18.jar is now a bootstrap jar which contains all libraries. You cannot directly depend on this jar. You should depend on Spigot/Spigot-API/target/spigot-api-1.18-R0.1-SNAPSHOT-shaded.jar, or the entire contents of the bundler directory from your server, or use a dependency manager such as Maven or Gradle to handle this automatically.
Please read the release notes for further information: https://www.spigotmc.org/threads/9-years-of-spigotmc-spigot-bungeecord-1-18-1-18-1-release.534760/#post-4305163
Thanks CafeBabe
yea i was just told that minecraft shifted to a bundler style jar
if I send an entity packet like spawn but the entity is far from the player, when the player comes near to the entity, will it show up? What about switching worlds?
weird parameters?
kekw maybe they don’t understand that maven just makes each group, artifact, and version more verbose
grade literally the same things just in 1 string
Say I have a list of YAML strings like this: ```yaml
example:
- "one"
- "cars"
how would I get all values of example?
getStringList("example")
so like config.getConfigurationSection("bad-words.").getStringList("bad-words.")?
List<String> list = getConfig().getStringList("example");
for(String line : list) {
// ...
}
erm wait
no
if your config look slike this:
bad-words:
- asd
- asd
then just getConfig().getStringList("bad-words");
truer words have never been spoken
100%
am back, for some reason my List is empty but my config.yml in my server contains a bunch of strings..
public static boolean isOffending(String text) {
String[] words = text.split(" ");
Bukkit.getLogger().info(Arrays.toString(words));
List<String> noNoWords = badWords();
Bukkit.getLogger().info(noNoWords.toString());
for (String s : words) {
Bukkit.getLogger().info(s);
if (noNoWords.contains(s.toLowerCase(Locale.ROOT))) {
return true;
}
}
return false;
}```
ignore the logging statements
public static List<String> badWords() {
return Tazpvp.getInstance().config.getStringList("bad-words.");
}``` badWords function
what about your plugin.yml ?
right😅
nice one 😛
this is the error org.bukkit.plugin.InvalidPluginException: Unsupported API version 1.18.2
this is in the pom file <version>1.18.2-R0.1-SNAPSHOT</version>
this is in yml file api-version: 1.18.2
why am i getting an error
do api-verison: 1.18
ok
hello I am have an issue with AdvancementDisplay.getType() intellij is not giving me any code errors but i'm getting build errors
oddly enough the error goes away when I simply comment the snippet out
class file is invalid for class org.bukkit.advancement.AdvancementDisplayType
Please remove or make sure it appears in the correct subdirectory of the classpath.
im not the most java savvy but it looks like there is no class but an enum there? (correct me if im wrong)
- 1.19 server and game
- api version:
spigot-api-1.19-R0.1-20220615.101427-27 - java 17
alright thanks so much 🙏 little late to respond sry
I have this obj.put("Mama", "Joe"); write();
and this public void write(){ try (PrintWriter out = new PrintWriter(new FileWriter("data.json"))) { out.write(obj.toString()); } catch (Exception e) { e.printStackTrace(); } }
and for some reason nothing happens
what is flush and close
flush makes sure all data has been written
so to the disk
as it stores it in a buffer first
in memory
and close closes the file handle i think
allows other code to access it
@glossy venture the IDE says that there is no need for out.close and i put out.flush like you said and it still did nothing as before
:(
now I have this try (FileWriter file = new FileWriter("data.json")) { file.write(obj.toJSONString()); file.flush(); } catch (IOException e) { e.printStackTrace(); } and it still does nothing and there are no errors
I open the json file and it's empty
I use file.write()
public class Json {
private static final Gson GSON = new GsonBuilder()
.setPrettyPrinting()
.create();
public static void write(Plugin plugin, String fileName, Object object) {
Path path = check(plugin, fileName);
try (BufferedWriter bufferedWriter = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
GSON.toJson(object, bufferedWriter);
} catch (IOException e) {
e.printStackTrace();
}
}
public static <T> T read(Plugin plugin, String fileName, Type type) {
try {
BufferedReader bufferedReader = Files.newBufferedReader(check(plugin, fileName), StandardCharsets.UTF_8);
JsonReader jsonReader = new JsonReader(bufferedReader);
return GSON.fromJson(jsonReader, type);
} catch (IOException e) {
return null;
}
}
private static Path check(Plugin plugin, String fileName) {
Path path = Paths.get(plugin.getDataFolder() + "/" + fileName + ".json");
try {
if (!Files.exists(path)) {
Files.createDirectories(path.getParent());
Files.createFile(path);
}
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
``` This is what I always use
Yea thats not what i am asking tho
@tall dragon if I have this json file:
{
}
``` will Files#write() write it in the middle line or the first line?
Pretty sure you can just have a. Empty file
I can't
pretty sure any write operation will overwrite the contents
ok so I shouldn't use it
Ah u need to append to it?
why doesn't this do anything?
obj is a JSONObject
try (FileWriter file = new FileWriter("data.json")) {
file.write(obj.toJSONString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}```
No idea
I would just load everything im the file as jsonobject. Add what i need to add and write it back using Files#write
debug
I get no errors and no output
Anyone knows how to check if a player placed a minecart? I want to add a tag to the cart of the player that placed it, but I don't know how to detect if a player placed a minecart.
EntitySpawnEvent
How do i get the player that placed it?
@EventHandler
public void onEntityExplode(EntityExplodeEvent e) {
for (Block b : e.blockList()) {
final BlockState state = b.getState();
b.setType(Material.BEDROCK);
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
public void run() {
state.update(true, false);
}
}, 20);
}
}
Not replacing the block list with bedrock, instead just replacing it with air.
Any fix?
yeah so debug it
Nvm found a solution.
String sql = "SELECT %s.%s,%s.%s,%s,%s,%s,%s FROM %s LEFT JOIN %s ON %s.%s=%s.%s WHERE %s".formatted(TABLE_NAME,UUID_COLUMN,PLAYERS_TABLE_NAME,NAME,CONTENTS,NUMSLOTS,MAXSLOTS,TEMPLATE,TABLE_NAME,PLAYERS_TABLE_NAME,TABLE_NAME,UUID_COLUMN,PLAYERS_TABLE_NAME,UUID_COLUMN, "HELLO");
LOL
public SkinProperty getSkinProperty(){
GameProfile profile = ((CraftPlayer) getBukkitPlayer()).getProfile();
PropertyMap map = profile.getProperties();
String texture = map.asMap().entrySet().stream().findFirst().get().getValue().stream().findFirst().get().getValue();
String signature = map.asMap().entrySet().stream().findFirst().get().getValue().stream().findFirst().get().getSignature();
return new SkinProperty(texture, signature);
}
This doesn't produce the right texture and signature of a player... can someone help me? 1.18.2
Hi guys, I've got this other plugin which has an "API" class with some public methods I want to access from my plugin. How can I do it? There's no wiki or docs at all for this plugin
In fact I had to decompile the jar to see this (but it's only for personal use, not selling/posting myself, don't worry)
1.18.2 has the PlayerProfile API why not use it?
Have you imported the jar to your project?
The world you want to check
Well a String is a String and not a world
You would have to get the world from the String
Bukkt.getWorld(name)
is there a clean way to do an if statement that accepts any candle type other than adding them all with || ?
switch?
Anyone comfortable with guice? I need some assistance with managing injections
Hello guys, what do I store when I want to store the exact copy of a block, so that whenever I, let's say, right click a different block, it can check whether that block is equal to my stored block?
like nbt data aswell?
Yes, the more specific the better
so i am trying to get the command output of Bukkit.dispatchCommand and I am trying to use a wrapper around the console sender to add this to a stringbuilder like shown in this post
https://www.spigotmc.org/threads/how-do-i-get-the-output-of-dispatchcommand-command-when-called-by-callsyncmethod.354521/
the thing is, the stringbuilder is just empty all the time, does dispatchcommand not use the specified sender to send the results?
all you really need it material, nbt data and facing direction
I see, that's what I figured as well. Is there really no other stuff I might need?
cant really think of any tbh
Alright, thanks for the input! 😄
Trying to ignite a creeper when it spawns, there is no .ignite or setFuse() for Creepers.
Any help is appreciated.
I am using 1.8 btw.
1.8
Ah that's the issue
Is there anyway to do it?
You'll have to use NMS then
I imported it into here but I can't really find what to do next
Did you import it with maven?
You should never use that menu if you have a maven project
Oh
https://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html
^ use this to install the jar to your local maven repo then add the dependency to your pom.xml
Ok thx
Is anyone familiar with PacketWrapper? How would I be able to spawn an area effect cloud with meta data?
there is a wrapper to spawn a living entity and one to spawn a (non-living) entity. The living entity wrapper allows to set metadata but the nonliving one doesn't.
An area effect cloud isnt alive right so I should not use the living entity wrapper?
