#help-development
1 messages · Page 184 of 1
php be like
$hostname = $_GET['HTTP_HOSTNAME']; // or similar
int* arr = (int*) malloc(10 * sizeof(int));```
public class MyClass {
~MyClass() {}
}```
The weirdest realization ever
who ever created this should burn in hell
that wouldnt compile
Just quit smoking /s
TELL ME THIS AGAIN, 10 YEARS AGO
oh, you can't
well I also can't stop
i wrote time machine in MachineScript
Cya 10 years ago
tho your current nature would be erased
and replaced with non-smoking one
damn this flight is on time
already boarding and it's only scheduled to depart in 1:15h
~mfnalex() {
free(data);
}```
@Override
public void finalize() {
data = null;
System.out.println("mfnalex's data has been erased");
}
// somewhere in main class
public static void main(String[] args) {
// entire universe
alex = null;
System.gc();
}```
I have a problem with my config file
everytime it saves, it deletes a bunch of data
when generated it looks like this
#--------------------------------------------------
# Join / Leave Messages
#
# Placeholders:
# - {player} : player's name
# - {nickname} : player's nickname
# - {prefix} : player's vault prefix
# - {suffix} : player's vault suffix
#--------------------------------------------------
JoinLeaveEnabled: true
JoinMessage: "&8[&a&l+&8]&r {prefix}{nickname}{suffix}"
LeaveMessage: "&8[&c&l-&8]&r {prefix}{nickname}{suffix}"
#--------------------------------------------------
# Chat Messages
#
# Placeholders:
# - {message} : chat message
# - {player} : player's name
# - {nickname} : player's nickname
# - {prefix} : player's vault prefix
# - {suffix} : player's vault suffix
#--------------------------------------------------
ChatMsgEnabled: True
ChatMsg: "{prefix}{nickname}{suffix} &8&l»&r {message}"
#--------------------------------------------------
# Spawn
#
# Delay : Milliseconds
# SpawnPvp : Cancel tp when hit by a player
#--------------------------------------------------
SpawnEnabled: True
SpawnDelay: 3000
SpawnPvp: False
SpawnPos:
==: org.bukkit.Location
world: world
x: 0.0
y: 65.0
z: 0.0
pitch: 0
yaw: 0
but when i try and save the config it deletes all of the notes and saves as: ```yaml
Join / Leave Messages
JoinLeaveEnabled: true
JoinMessage: '&8[&a&l+&8]&r {prefix}{nickname}{suffix}'
LeaveMessage: '&8[&c&l-&8]&r {prefix}{nickname}{suffix}'
ChatMsgEnabled: true
ChatMsg: '{prefix}{nickname}{suffix} &8&l»&r {message}'
SpawnEnabled: true
SpawnDelay: 3000
SpawnPvp: false
SpawnPos:
==: org.bukkit.Location
world: world
x: -251.75343445139748
y: 63.0
z: -174.66100164978275
pitch: 13.800111
yaw: 79.657906```
this is what im currently using to save and load my code
public void SaveConfig() {
saveDefaultConfig();
}
public void LoadConfig() {
// Default Config
getConfig().options().copyDefaults();
saveDefaultConfig();
}
and i have some code in a seperate file which also saves the config ```java
Amenities.getPlugin(Amenities.class).getConfig().set("SpawnPos", Loc); Amenities.getPlugin(Amenities.class).getConfig().options().copyDefaults(); Amenities.getPlugin(Amenities.class).saveConfig();
Sorry for the long post, I have been trying to fix this for a few hours now
if i have one of the key it does it once
but if I have two or more, it will run twice??
why is this happening.??
?paste that jeez
@vocal cloud
mfw server crash mod
Honestly you should just delete the switch and use an array and an if statement
array1 = [coinamnt1,coinamnt2];
array2=[gemamnt1,gemamnt2];
rand = randgen.get();
if(rand >= array1.length) {
// gen message and do the other stuff
} else {
// gen gem message and other stuff
}
Reduce that code by 99%
looks outdated + spaghetti
Could probably be condensed to 10-20 lines
what is a loadConfig?
why do you even need this
yeah but, how would i fix the doubling?
You'd fix it by not having a switch
This is the best way to do it
int toAdd = randoms[rand];
event.getPlayer().sendMessage(color(MobGens.getPlugin(MobGens.class).getConfig().getString("prefix") + " &7You opened a crate and received: &b$" + toAdd));
balance = storage.grabDoubleParsed("balance", event.getPlayer(), false);
balance+=toAdd;
storage.setVariable("balance", event.getPlayer(), balance, false);
done
in 5 lines
Yeah, except you can't also handle gems that way
instead of 21 switch
Which you can just use an if and subtract the length of the previous array to get the position in the next
Yeah but you'd still need to if(ran.length >= firstArray.length) {
int value = gems[ran - firstArray.length];
}
That's how actual spigot methods look like
Can you use Hex Codes in Player Titles?
i guess with textcomponent you can use them everywhere
I have chat working just fine but for some odd reason hex codes aren't working for me in player titles
Title or Sub Titles. They are appearing white.
hmm
why not DI
tho ...Config() methods usually eat comments
only leaving head comments(which are on top of yml) untouched
Not sure if they're handled different. Anyone know more on that?
i guess guys are sleeping
The white color is the sub title.
The color is a message being sent to the player.
show your title sending code
actually colorizing code too
i guess you just do sendTitle() so first part is not needed
never used hex codes no idk 🙂
mostly worked for 1.12 so never really paid attention to Hex colors feature
String title = formatToHex(plugin.getConfig().getString("Regions." + regionName + ".Title"));
String subTitle = formatToHex(plugin.getConfig().getString("Regions." + regionName + ".SubTitle"));
player.sendTitle(title, subTitle, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE);
I am just confused why it works for chat and not titles but I have seen other plugins out there sending hex codes to titles.
just learnt new JDK features
First time working with them for me
i mean this is a default code for sending
what is your formatToHex code
Snagging that now, it's not mine, just a public util from a spigot thread everyone said it works for them which it does but not titles.
public static String formatToHex(String message) {
Pattern pattern = Pattern.compile("#[a-fA-F0-9]{6}");
Matcher matcher = pattern.matcher(message);
while (matcher.find()) {
String hexCode = message.substring(matcher.start(), matcher.end());
String replaceSharp = hexCode.replace('#', 'x');
char[] ch = replaceSharp.toCharArray();
StringBuilder builder = new StringBuilder("");
for (char c : ch) {
builder.append("&" + c);
}
message = message.replace(hexCode, builder.toString());
matcher = pattern.matcher(message);
}
return ChatColor.translateAlternateColorCodes('&', message);
}
Result, works perfectly in chat.
yeah we got that it works in chat
Which makes me think that tiles do not support it or utilize a different way.
Not sure entirely though. Some individuals have gotten it to work.
Could be, I'll try it!
good luck with packets
tho you can probably do this on paper
but would need BaseComponent's
instead of strings
kyori adventure stuff
Okay, thanks. I will look into it
Anyone. Explain what's the point of using nested classes
if you only want a class used in one place
keep things neat and in place
How can I randomly rotate a schematic?
you dont really want to compile your pattern over and over again
How can I randomly rotate a schematic with the we api
look up the rotate command
see how they do it
do it like them
Uhm kk.
what is better, making a plugin-like minigame library, or making a custom server jar to use as the library
I added a jar to my plugin as a dependency the scope is set to compile but when I try compile my plugin using maven package I get this error
package com.gmail.nossr50.api does not exist
I know that jar will be in my plugins folder does that mean I would have to compile it into my plugin? and if i didn't how would i get it to work
If you want to add the dependency to your jar you want to use compile. If the API has a jar u can put provided.
Make a lib if you think you need an entire fork for your specific uses you are just wrong. If you plan to do other patches and performance tweaks specifically for mini games go for it otherwise stay away from forking
Anyways, does anyone know how to make custom player heads 1.19?
I've tried but it just gives me an alex head
ItemStack item = new ItemStack(Material.PLAYER_HEAD);
SkullMeta meta = (SkullMeta) item.getItemMeta();
GameProfile profile = new GameProfile(UUID.randomUUID(), null);
profile.getProperties().put("textures", new Property("textures", texture));
try {
Field field = meta.getClass().getDeclaredField("profile");
field.setAccessible(true);
field.set(meta, profile);
}catch (Exception exception) { exception.printStackTrace(); } finally {
item.setItemMeta(meta);
}
i think you need a signature, idk though
npc skins didn't work for me without it
but you are doing skulls, so i'm not sure
well it's more of the api is a class in the jar
Oh yes 1s
Yea the only thing is the jar has to be an active plugin.
It is
i just can't do anything if my plugin won't compile
Make sure u put provided then
public ItemStack skull(String head) {
ItemStack skull = new ItemStack(Material.PLAYER_HEAD, 1);
SkullMeta skullmeta = (SkullMeta) skull.getItemMeta();
GameProfile profile = new GameProfile(UUID.randomUUID(), null);
profile.getProperties().put("textures", new Property("textures", head));
Field field;
try {
field = skullmeta.getClass().getDeclaredField("profile");
field.setAccessible(true);
field.set(skullmeta, profile);
} catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException x) {
x.printStackTrace();
}
skull.setItemMeta(skullmeta);
return skull;
}
You were right, you have to provide an UUID for the game profile based off the texture.
thanks man
How can I rotate schematics before I paste them?
I need to move an NMS Player NPC relatively in 1.8.8, but i'm having trouble with fixed-point numbers. this is my code:
connection.sendPacket(new PacketPlayOutEntity.PacketPlayOutRelEntityMove(
fakePlayer.getId(),
(byte) ((newLoc.getX() - loc.getX())* 32),
(byte) ((newLoc.getY() - loc.getY())* 32),
(byte) ((newLoc.getZ() - loc.getZ())* 32),
followEntity.isOnGround()
));
Which results in the player slightly desyncing with the real location.
Hi. I wanted to check if EntityDamageByEntityEvent was cancelled with @EventHandler(ignoreCancelled = true), but it seems to not be working on worldguard. Anyway, is there any other ways with I can check if player got his damage or not?
if (!((p.getHealth() - e.getDamage()) == p.getHealth()))
I tried this ^ but that check is not working too.
Can anyone help?
You want to do it like that
connection.sendPacket(new PacketPlayOutEntity.PacketPlayOutRelEntityMove(
fakePlayer.getId(),
(short) ((newLoc.getX() * 32 - loc.getX() * 32) * 128),
(short) ((newLoc.getY() * 32 - loc.getY() * 32) * 128),
(short) ((newLoc.getZ() * 32 - loc.getZ() * 32) * 128),
followEntity.isOnGround()
));
P.S you need to check if the player move less the 8 blocks,
if the player moved more then 8 blocks you need to use Teleport Entity
if you want to check if player got damage you don't do
(p.getHealth() - e.getDamage()) != p.getHealth()
because it will almost always be true expect if damage is 0
if you want to check if player got damage by other entity you just do
@EventHandler(ignoreCancelled = true)
public void on(EntityDamageByEntityEvent event) {
if (!(event.getEntity() instanceof Player player)) return;
if (event.getFinalDamage() == 0) return;
// Do something
}
thanks.
ahh, so i forgot the 128.
Also, the entity is being tracked in real time, so theoretically it will never have to teleport
but, thanks for the reply!
You welcome.
P.S it is looking like you missing some because java knowledge so you should need to learn java before using spigot api
ok
btw next time if you don't know why packet doesn't work use https://wiki.vg/Protocol
i did
and i just realized why your code diuffers from mine, i used the waybackmachine to view wiki.vg when it was updated for 1.8.8, and thats slightly different
no need for waybackmachine
Can some one help with this? I tried setting scope to provided and unticked it as a dependency under modules but still no luck
oh cool, i didnt know that existed, thanks! though my implementation, based on this: https://wiki.vg/index.php?title=Protocol&oldid=6314#Entity_Relative_Move looks like it should work
but it still doesnt
how would I go about identifying an inventory?
like distinguishing one person's gui from another
get the inventory owner
i mean like
let's say i have a settings menu (a gui)
a normal player can only change their own settings
but an operator can change another player's settings
nvm
How would I add a local dependency to my project?
basically I just want a way to store nbt data in an inventory
but that's probably not possible
there are way better ways of approaching this
just have a separate inv for each player then if an op edits another player's settings, update the current player's inv
hey, I created an npc, but I dont know how to spawn it. can someone help? 1.19.2
the "another player's" part is the thing i'm struggling with
i need to identify the owner of the settings
how are you handling custom inventories rn
because that will either make your life far easier or be a pain in the ass
you need good infrastructure
i'm not yet handling inventories atm
i just need the general idea on how to identify
i dont know if this is a good solution but i could make a single borer item have nbt
which stores the UUID of the owner of the settings
but that's probably not the best idea
public class PlayerSettingsInventory extends CustomInventory{
private final UUID player;
public PlayerSettingsInventory(Player player){
this.player = player;
}
@Override
public Inventory getInventory(){
//do inventory shit regarding player
}
@EventHandler
public void onClick(InventoryClickEvent event){
//do stuff here
}
}```
with a good backend you should be able to do something like this
where each instance of a class is a certain palyer's gui
no need for any nbt stuff
an inventory is tied to a class
utilise OOP
e.g if i open this inventory to a player, can i get that custom class via a bukkit method?
could use InventoryHolder
or keep track of all inventories and handle that accordingly
yea the part i'm struggling with is being able to get that owner via a bukkit method
wdym?
InventoryHolder gives you the owner
in that code i just gave you it's as simple as this.player
just need to ensure the inventory clicked is the correct one
?jd-s
so should I implement InventoryHolder..?
inventoryholder itself is a player
or the other way around'
you can get the holder of an inventory
and it will be instranceof player
((CraftArmorStand)((Object)standTires)).getHandle().setLocation(x, y, z, yaw, pitch);
Why is setlocation not working in 1.19.2 in 1.12.2 it was working fine
public class CustomInventory extends InventoryHolder{
public Inventory getInventory(){
return Bukkit.createInventory(this, 9, "Title");
}
}```
a lot of people do this
im not sure if you open an inventory to player it will automatically set the holder
no it doesn't
i have never seen this (when hovering above spigot dependency) can someone explain??
a vulnerable dependency?
are you sending a move packet later on?
and whats up with all that casting
Okay so yesterday i played around with aliases and this is what i ended up with
Objects.requireNonNull(getCommand("withdraw")).setExecutor(new Commands());
Objects.requireNonNull(getCommand("withdraw")).setTabCompleter(new TabComplete());
CommandMap map = Utils.getCommandMap();
Command cmd = Objects.requireNonNull(map).getCommand("withdraw");
List<String> aliases = Objects.requireNonNull(cmd).getAliases();
aliases.addAll(config.getStringList("withdraw.aliases"));
cmd.setAliases(aliases);
System.out.println(getCommand("withdraw").getAliases());
[banknote] gets printed which is correct, however running command using banknote doesnt do anything
getCommandMap() essentially does this
final Field f = Bukkit.getServer().getClass().getDeclaredField("commandMap");
and sets it to accessible
you use reflection on every getCommandMap call?
its only ran once
damn your abuse of Objects.requireNonNull makes this hard to read
Hi, I'm developing a UHC plugin, but I would like that when I generate a map, there must be a Roofted Forest biome within 200 blocks of the center. How can I do this?
¯_(ツ)_/¯
what is a UHC plugin?
ez fix, forgor to register
UHC = Ultra HardCore, it's just a plugin to create sort of a battle royal on minecraft, but it doesn't really matter for what I wan't to do
now time to clean that mess up
i think its not possible to force the world generation to make a speficted biome WITHIN a given radius
yeah generally world generation is ass to make
But I alsoran into a problem
Is it possible to do it on the whole world ? Like a single biome
Generually... I did MySQL before, mostly with not that many errors... However, I am fixing and repairing my code - because it looks like shit -, and I removed most of the "static" izék from most of the voids. Now my plugin cannot boot up, because its saying that connection is null.
First class (that one that gets and sets data from MySQL):
public MySQLManager m = new MySQLManager();
public void voidName() {
try {
PreparedStatement ps = m.connection().prepareStatement("sqlcode comes here");
ps.executeUpdate();
} catch (SQLException e) {
Bukkit.getLogger().warning("§cHiba törént az adatbázisban!");
e.printStackTrace();
}
}
Second class (the manager itself):
public Connection connection;
public boolean isConnected() {
return (connection == null ? false : true);
}
public void LoadDriver() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (Exception ex) {
ex.getMessage();
}
}
public void connect() throws ClassNotFoundException, SQLException {
if (!isConnected()) {
try {
connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + name + "?useSSL=false", user, pass);
} catch (SQLException e) {
Bukkit.getLogger().warning("[Hiba] Hiba a MySQL-ben!");
Bukkit.getLogger().warning("[MySQL] Hiba: " + e);
}
}
}
It is, by settings properties, but for an UHC its not a good idea. Better leaving the plugin use the default settings, and let it generate fully random worlds.
Should I set it back to static...?
you have to call connect() method before voidName() one
I already did
also return (connection == null ? false : true); can just be return connection != null
This is how it looks like:
SQL.LoadDriver();
SQL.connect();
data.voidName();
data.voidName1();
but in code you provided you are making second instance of public MySQLManager m = new MySQLManager();
are you doing it async?
assuming SQL and m are not same instance
how are you getting SQL
// few lines below public class Loader
public MySQLManager SQL;
public MySQLGetterManager data;
// later in code when plugin starts up
getServer().getPluginManager().registerEvents(new MySQLManager(), this);
getServer().getPluginManager().registerEvents(new MySQLGetterManager(this), this);
this.SQL = new MySQLManager();
this.data = new MySQLGetterManager(this);
try {
SQL.LoadDriver();
SQL.connect();
data.voidName();
data.voidName1();
so its not the same
this.SQL = new MySQLManager(); here you are making new instance, and also making new instance public MySQLManager m = new MySQLManager(); inside of data class
This is inside the Loader class (main)
Meanwhile, the path I get the error to, is another class
They must be named the same?
(the references)
reference must be same, yes
you cant create new object
you are connecting with object A, but using connection from object B
so thats why it always was null
because before I was using plugin.SQL.connection() and not (from now on) d.connection()
Anyway thanks :D
Myeah
But like concurrent maps such as the concurrent hash map and concurrent skip list map, null keys are not admitted in which containsKey and get != null are basically the same
read the note in the javadoc on opening inventories in the close/interact event
From your error it looks like I spoke too soon
AcceptRules.java:44
something in there is null
Don't detect inventories by their name
they can be faked
If someone else names an inventory that it will break stuff
Let's say you have an item rename plugin for example. I rename a chest to your inventory name then it will cause issues
You either track the inventory instance or give it a custom inventory holder
you have an gui instance so use that
impossible.
change all your if(event.getView().getTitle().equals(guiInv)) to if(event.getInventory() == gui))
are you getting in some infinite loop by closing/ reopening inv?
mh, kid, you still have a lot to learn about life🗿
whats on AcceptRules.java:44
you are also using the wrong event, line 42
use the close event
and don;t cancel the event
just to be sure, does a invclose event gets fired when players gets kicked with an inv open?
Thats wrong
Well yeah that's going to cause an infinite loop
you don;t call close in the close event
in the close event you call open on a 1 tick delay
Pseudo code```java
if (event.getInventory() != gui) return;
Bukkit.getScheduler().runTask( plugin, () -> { player.openInventory(gui) } );```
it calls runTask in the Bukkit scheduler to run that lambda
it runs some task a tick later
where there are 20 ticks in a second in a normal situation
dont pass in null
simple
how do you get your plugin? di or singleton?
pass yoru plugin instance to your listener to use as plugin
?di
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
so in your main class when you normally use new AcceptRules() you would use new AcceptRules(this)
and add a constructor to AcceptRules to take a Plugin instance
would look like
public class AcceptRules implements Listener {
private final MainPluginClassName plugin;
public AccpetRules(MainPluginClassName plugin) this.plugin = plugin;
}
You just need to pass an instance of your plugin to your Listener
don;t need singleton. Your plugin instance IS a singleton
well if u dont know what a singleton does
new MyPlugin() 🥲
then you never knew how to make one
in the first place
just saying, no one will turn into a cannibalist and eat you alive because you dont know what a singleton is
When you call openInventory with an inventory already open it will trigger a close event. If you are already IN a close event you are firing teh same event over and over
So you have to delay the opening to allow the current close event to finish
tbh cant spigot just like
do this internally
Not without as lot of internal checks to see if it's already fired the event
too much work 🙄
its simpler to just fire events and let plugin devs sort it out 🙂
This channel tends to turn on big egos before they get too rude.
eitherway, here we have a saying that
two types of people never learn, the embarassed and the egotistical
point is, you shouldn't refrain from asking questions or stating your lack of knowledge out of embarrassment
So long as you know basic Java, no question will be ignored.
hey i have a problem, i created a bossbar with color and text but when i set it to the players it is just gray and it looks kinda weird https://imgur.com/a/gXyxBeJ
im not seeing much on that screen
looks like just the mid sections
do you know && is a thing?
yeah it is the bar that has no color
the title works
but also the segments and the updatemethod works
Sorry I can;t work out anything in the pic
per is invalid
^^
i can see whats happening in the picture
basically, the bossbar is distorted
the bossbar is supposed to be purple
yet some parts are invisible
but i set the bossbar color to blue why it isn`t blue?
and some are black
1.19
seconds / 1.0?
ok
but the progress works
the bar progress moves only the color isnt there
there is the vid
isnt your resourcepack just fucking up?
lmfao
public void onSignCreate(SignChangeEvent e) {
Sign sign = (Sign) e.getBlock().getState();
if(Objects.equals(e.getLine(0), "[CFGames]")) {
switch (Objects.requireNonNull(e.getLine(1))) {
case "snowrace" -> {
Bukkit.broadcastMessage("t");
sign.setLine(0, ChatColor.DARK_GRAY + "[CFGames]");
sign.setLine(1, ChatColor.GOLD + "Snow Race");
sign.setLine(2, ChatColor.GRAY + "0/7");
Bukkit.getScheduler().runTaskLater(main.getInstance(), () -> {
sign.update();
},10);
}
case "snowballfight" -> {
sign.setLine(0, ChatColor.DARK_GRAY + "[CFGames]");
sign.setLine(1, ChatColor.GOLD + "Snowball Fight");
sign.setLine(2, ChatColor.GRAY + "0/10");
Bukkit.getScheduler().runTaskLater(main.getInstance(), () -> {
sign.update();
},10);
}
}
}
}
``` Does someone know why the sign is not updating? I tried with out the Scheduler to run it instantly but its not working. I get the t in the MC chat logged so I don't really get it what wrong is in the code.
given the event is cancellable my best guess is that the setLine method is overriden after the event is called
hoping there is an @EventHandler
Yep it is just didn't copied it into the message
How can I set the value of the "name" field in GamProfile?
I make It like this:
entityPlayer.getProfile().getClass().getField("name").get(entityPlayer.getProfile())
But I get this exception:
https://paste.md-5.net/femovotiqo.bash
not ended yet
should i made db columns notnull by default in my db lib?
ends in like 3 hours 33 minutes
tuff golem is the worst
its low lvel
its pointless after getting a dia pick
and u might be able to change the loot it gives with spigot
itll open so many possibilities
better than a few useless plants and a mob that we will forget in a few hours
and it can open the possibility for a new minigame on servers
a rascal hide and seek and see who gets a certain item first
?
You need to get the obfuscated field name
In your case the field "name" doesn't exist
It's probably named something else
I used getFields() and there arent any fields
Try getDeclaredFields
Yeha it worked
And pls just use a local variable lol
brr

combing that with reflections, basically i have no idea what im doing
How can I get the exact class with Reflections? Because when I get the nms World, I get the nms worldserver
you need Level
Without mappingss
good luck not using mappings
Im using reflections for mulitversion support
?paste
For version independent https://paste.md-5.net/bebavosuyu.java
what are u doing
What are you diong
blank consumer?
fucking up with generics and reflections
cring
basically trying to do this with reflections
brah
making games is cringe
I think it's been 5 hours since I started implementing pathfinding and it feels like I have not even started
classic
I just don't want lame stuff like entity overlap in a grid-based df-style map
but as it turns out if you're doing a df/rimworld style game, disallowing units from overlapping is uh
well it doesn't really work
it does, it just blocks pathing
well yeah, sort of permanently too, there is no good condition to avoid it
if you want overlapping you shoudl add layers
I'm just sort of bypassing the issue
there's an incremental speed debuff for stacking entities in the same grid space and entities will do a quick adjacency check to see if there's an alternative square they can use that is empty
so basically there's a justifiable reason to making corridors with higher circulation wider
without it ruining gameplay
just store it as seconds remaining?
store a unix timestamp, it will save you on headaches
also don't use yml files, use a database
but they probably only want to "countdown" while the player is online
i'd just use the player's PDC
no need for any external storage
oh you want to store a fixed date? yeah then ofc go for a timestamp
I thought you wanted to ban them after "X hours of playtime" and not "next thursday at 3 pm"
sure
just turn the target date/time into a timestamp and save it as long on the player's PDC
then when they join, compare the current timestamp with the "ban date" and if it's > than that, kick them
I keep forgetting that exists
PDC is the most beautiful thing ever added to spigot
I was already an old man when it got added, it's just not a part of my workflow
I mean
young and hip
as I still am
was back then too
I only found out about it in 1.16
and it was added in 1.14.1
since 1.16.3, even chunks have a PDC
and worlds too, since 1.18 or so
as a long
a timestamp is just a long / large number
ur just a long / large number
e.g. System.getCurrentTimeMillis() returns a unix timestamp
I'd do it like this:
private static final long DEFAULT_PLAY_DURATION = 10 * 24 * 60 * 60 * 1000; // 10 days * 24 hours * 60 minutes * 60 seconds * 1000 milliseconds
private final NamespacedKey endDateKey = new NamespacedKey(myPlugin, "endDate");
onJoin:
long timeNow = System.getCurrentMillis();
long timeEnd = timeNow + DEFAULT_PLAY_DURATION;
player.getPersistentDataContainer().set(endDateKey, PersistentDataType.LONG, timeEnd);```
you should just check it on join and then again every second or so for all online players
Ofc not?
Why would it be
brah
unless your server is known to run slow just make a task that will ban them after a set amount of ticks
Inagine the huge amount of physics getting done on every tick
and make that tick count equal to the time to ban
Just comparing two longs is literally nothing
just use a delayed task
You could compare it 100 times per tick without ANY problems
joke's on you, his server has 10000000 concurrent players
This reminds me, i need to reinstall my rpi tomorrow
my man
hey my bank account got hacked, spread the love
I don't trust banks anymore send me bitcoin
2x0=0, checks out
what if im in debt? will u just take even more money?
no, only the bank does that
lmao
Is there any tutorial on ConfigurationSerializable?.
the javadocs explain everything
declaration: package: org.bukkit.configuration.serialization, interface: ConfigurationSerializable
Ok
that requires two lines of NMS
that's two lines too many
I wrote this for offline player PDC:
https://github.com/JEFF-Media-GbR/JeffLib/blob/master/core/src/main/java/com/jeff_media/jefflib/data/OfflinePlayerPersistentDataContainer.java actual class
https://github.com/JEFF-Media-GbR/JeffLib/blob/master/core/src/main/java/com/jeff_media/jefflib/PDCUtils.java#L539 method to get the PDC from a player
then where are you going to get the "leave date" from?
do you actually need the data of offline players?
you shouldnt change their remaining time every second
you should rather just only store the "end date" in the first place
I mean, imagine you have an appointment at the barber in 3 days. you wouldnt write down "appointment in X thousand seconds" then count it down by one every second, you'D just write down "thursday at 3pm"
on first join, just e.g. do this:
end date = current time in milliseconds + allowed duration in seconds * 1000
now, you can just check every second whether the current time in milliseconds is >= the end date you saved
if yes, their time is over
yes 🙂
I mean you don't even have to use milliseconds, you could just use seconds
I only used milliseconds in this example because that's what System.currentTimeMillis() returns
the TimeUnit class is also very handy to convert
e.g. TimeUnit.MILLISECONDS.convert(3, TimeUnit.DAYS) or sth like that
that would return you the amount of milliseconds that equals 3 days
yep
:3
How can I cast Block to a Chest?
Thanks
and be sure to check if it actually is a chest before casting it
the fields?
the "on Join" part is obviously a listener that listens to PlayerJoinEvent
How to find out which world the player is in(example: overworld)
World#getDimension
no
you could e.g. do this
myMap.put("mfnalex", null);
now it containsKey("mfnalex") but .get("mfnalex") would be null
I need some help with nMessage library, is posible to use it to send a list of messages but on replacing each variable from each value that are diff on the next line?
me when doing reflections
that's personal preference
di
DI leads to so much useless code imho
it does not
people claim it's better for unit testing but those people havent heard of mockbukkit
depending on the use case tho, right? when you want your plugin to be extendable with dependant plugins di is the way to go
sure it depends. if you just need your main class in a listener to get a namespacedkey, then a static instance getter is totally fine
then you can do what you want 🙂
i mean there isnt really a difference between passing "this" to every new object, or to just provide a getInstance() method that returns the same thing
it's something like "minecraft:dirt"
technically theres always a way to get the plugin instance, by using the PluginManager
you dont even have to have an instance refernce yourself
stuff like PersistentDataContainers heavily use NamespacedKeys
tf
sure, but then you gotta cast it, and the plugin manager needs to look it up from a map or sth
yeah, that's why I prefer a static getter
should be a HashMap tho, so not too much work
javaplugins are a singleton by design anyway
sure, but still, might just as well provide a getInstance() method yourself
true
nothing of these is really wrong or right, I think it's just personal preference
then I dont understand why people shame others for using static instance references
plugin instance getters
u mean geti() and stuff?
java.lang.IllegalAccessException: Can not set final int field me.fourteendoggo.database.object.DummyPlayer.level to java.lang.Integer```
does this mean i cant use `field.set(integerObj)` where the type is an int?
that's 100% fine
not in here its not
made the field accessible before
weird
theres definitely some things that require non static references and stuff... just makes it easier for other people to expand on your code
I have a string list on the config which has the next values and my goal is to know how to send the list 1 time but replacing each variable from a List. Im using nMessage
Command:
Help:
- " &6%command% &7Help: "
- ""
- " /%command% %usage% - %description%"
my job for example would kill me if I ever used static for pretty much anything (of course with exceptions)
not preffered
but always possible 🙂
breaking your computer is also possible
then how about we start with yours 🙂
most inconvenient things are always possible
its more convenient than not being able to get an instance at all
what is nMessage
What?
???
how can you not be able to get an instance at all
just split the list into header body and footer and loop the body as many times as needed
I was being dramatic but sure, I was thinking from the perspective of other plugins getting your instance
how might I check if the player is in a new chunk?
that's another case
cache old chunks, compare to current chunks
setting a final field with Field::set should work right?
How lmao
you get a HashMap, cache the player you wanna check with their current chunk, then every time you do whatever you check whether their current chunk is still the same chunk
do you know how to cache an object? @raw prairie
Is a library for sending message depending on the player locale
anyone even listening lol
Not really
do what shreb said then
sorry I havent worked with Reflection at all really :/
?tryitandsee
tas
there
there ya go
yes
dont you have to remove the final first
Hey man, can we go back in our thread, I got some questions to ask you
usually setAccessible(true) is enough. if the security manager is annoyed, then you also need to remove the final modifier
setting an int field to an Integer should normally work?
im like 90% sure you need to remove the modifier
static void setFinalStatic(Field field, Object newValue) throws Exception {
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
proudly stolen from SO
i never needed that
its not static
How can i end a task from another class?
?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.
generally learning java will help you achieve that
How can I make it so that the data that I need is displayed in the tablist
lets your command class implement TabCompletor and override the method to return a list of completions
assuming your talking about chat
im talking about tablist(without another plugin besides papi)
declaration: package: org.bukkit.entity, interface: Player
oh even headerfooter in one method
?paste
Can u help me fourten?
what do you want to show
I want to apply tab completion for everything so when you type the command its recommend you the posible arguments or sub commands and then args of each sub command
I dont know if i have explained
I have that tab complete method
you need a way to check the args.length of tabComplete
BukkitExecutor handle the commands
This handle arguments and sub commands
tell me what possible completions you want
where on executor or argument?
uh i mean what are the possible syntaxes for your command
BukkitExecutor = normal command
BukkitArgument = an argument or sub a command
perfect
you know how this works?
its hipotetical case but just to see how it would be done
it would allow /trade request /trade cancel /trade accept /trade decline /trade help
cuz youre checking what the length of your args is
/faction - base command
/faction list - command argument
/faction info <name> - sub command
So, when you type only "faction should recommend, list and info"
Once you type "faction info " should recommend factions names
List<String> onTabComplete(String[] args, CommandSender sender) {
return switch (args.length) {
case 0 -> showHelp(sender);
case 1 -> {
List<String> completions = Arrays.asList("list", "info");
yield StringUtil.copyPartialMatches(args[0], completions, new ArrayList<>() /*buffer*/);
case 2 && args[1].equals("info") -> showFactions(sender);
}
}
}```
that stringutil thing (bukkit class) just checks the already entered things
so if you would do /faction aaaaa it wouldnt longer display list and info
Because i have a List<BukkitArgument> where i keep each arg name, etc, execute, tabcomplete method
I mean the first part is done
Just to know when i need to rn the BukkitArgument#tabComplete()
I dont think im explaning my self
so get the BukkitArgument based on the input?
That is to you to see how it works the command
uhh does that do anything?
Wait the permission part is wrongly coded
Could someone help me fix the bug in plugin I made year ago? I have been coding in C# recently so I don't remember java. https://hastebin.com/afuxilihuv.java the plugin drops steve head with player one for some reason
So how would i call the tabComplete from BukkitArgument?
heres the problem
pass player instance
How?
do you have a player instance in that section
yea, player2
for the class
okay, do you set player 2 in that section
No
I do not set player2 in the main class
ok
send your main class on one too
alright
Plugin drops unwanted item
is it normal that this prints nothing?
getFIelds prints the fields ffrom Member.class
looking at your main class your not passing in a real player instance
should have all these
so, what could I do
you need a player instance what you can pass in on that if statement
could I get an example 🙂
for (Player check : Bukkit.getOnlinePlayers() {
if (cache.checkForNewChunk(check)) {
// all of your code
}
}
https://pneumonoultramicroscopicsilicovolcanoconiosis.club/Ezi8pzRi
StringBuilder builder = new StringBuilder();
for (Potion value : Potion.values()) {
builder.append(value.getName()).append("\n");
}
ArmorStand as = (ArmorStand) e.getPlayer().getWorld().spawnEntity(e.getPlayer().getLocation(), EntityType.ARMOR_STAND);
e.getPlayer().sendMessage(builder.toString());
as.setMarker(true);
as.setGravity(false);
as.setCanPickupItems(false);
as.setCustomName(builder.toString());
as.setCustomNameVisible(true);
as.setVisible(false);
e.getPlayer().addPassenger(as);
https://pneumonoultramicroscopicsilicovolcanoconiosis.club/OjAr0BCE
How can I make multi line names?
multiple holograms
is that really the old way?
i guess thats the way
can someone just test this for me, im getting no output altho it should
for (Field field : Field.class.getDeclaredFields()) {
System.out.println(field.getName());
}```
how i get the distance between two locations, with x, y and z distance values??
Location#distance
Ugh... so I just found out how terrible the BlockExplodeEvent is to work with
so will this check if a player is in a new chunk or not
because if hte player is in a new chunk
I want it to execute my ode
@remote swallow
what will cache.checkForNewChunk return if it is a new chunk
I am aware of this method, but it gives me the distance between the 3 axes, I would like to know the distance of x, y and z
it will return false if its an new chunk
and reutrn true if its an old chunk
thats a bad idea
change the if to if (!(cache.checkForNewChunk(check)))
alreadyt did lol
no idea if you need testing on that still but I'm also getting no output on java 17
wtf is that domain
weird
anyways the original issue was this
where this is my code and it fails at the field::set
it should be doing unboxing to an int automatically when receiving an int so i dont think thats the problem
api notes say this
Hi guys can someone help me?
When I start my plugin first time it is creating Config.yml with all datas but plugin doesn't get that datas for using. After that when I reload plugin it is now plugin see those datas. Let me show with picture
Why?
record fields immutable ig
i dont have that variable created before
- String cannot be resolved to a variable
- Syntax error on token "String", ? expected after
this token
- entry cannot be resolved to a variable```
what
final fields seem to not be included in Class::getDeclaredFields?
what
not responding to you
i dont get it
what?
I was going to say that the fields where final
Amogus
Do i lose anything from UUID value when i turn it to an String?
record fields seem to be not accessible thro reflections
no
convert it back using UUID.fromString
thx
hmm it seems to have other ways
How can i stop particles from mooving away when spawing?
hey, what is TeleportCause and how do I get it?
record fields ::set doesnt work?
No, they’re transparent immutable data carriers
so you cant change the value of their fields thro reflections?
Nope
smh
That’d violate the java specifications concerning records
yes i understand that, but relfections has always been a hacky solution so i thought that'd work 🙄
uhh reflection whatever
Yeah
i guess now create a class for this :/
or i might use some constructor instead
actually yeah
Its a bit weird, but it does make sense to encapsulate the record components strongly even against reflection
anyways is there a way to get the (default) constructor of a record, like the one declared with record Whatever(...) {}?
can anyone tell me how to edit download jar files in intellij idea?
i believe its clazz.getConstructors()[0] tho
Is there a way to fix this at BuildTools?
applyPatches.sh: line 2: $'\r': command not found
Rebuilding Forked projects....
applyPatches.sh: line 6: $'\r': command not found
applyPatches.sh: line 7: syntax error near unexpected token $'{\r'' applyPatches.sh: line 7: applyPatch() {
'
Error compiling Spigot. Please check the wiki for FAQs.
If this does not resolve your issue then please pastebin the entire BuildTools.log.txt file when seeking support.
java.lang.RuntimeException: Error running command, return status !=0: [sh, applyPatches.sh]
at org.spigotmc.builder.Builder.runProcess0(Builder.java:973)
at org.spigotmc.builder.Builder.runProcess(Builder.java:904)
at org.spigotmc.builder.Builder.main(Builder.java:703)
at org.spigotmc.builder.Bootstrap.main(Bootstrap.java:27)
( I just woke up and did this ) It did not work.
Yeah
getDeclaredConstructor(params)
the thing is that i dont know the params classes
Thata fine
🤔
ig smth like this
switch to ij
not enough requirements
@tardy delta
declaration: module: java.base, package: java.lang, class: Class
Look at the example
2475: <illegal opcode> Setar : (Ljava/lang/Object;)Ljava/io/File;
whats this code?
looks like someone tried to manually edit a jar
@ivory sleet fixed it 🙏
My code isn't working as intended, its intended purpose was to check if a player was at a new chunk, and paste a schematic near the player
it doesnt do that
but it produces no errors
forgot that i had two annotations for db fields: Column and Id
Hey, can we go into the thread #1030635947093663754 ?
I need some help
Hey
Use getDeclaredConstructor(params)
Cuz [0] is not guaranteed to be the canonical constructor
But else noce
Im trying to check if a chunk is new and near the player
and if it meets the requirements
ah thats what you were trying to say me
um you are actually putting full chunks into your Map
memory leak go brr
me?
liek clazz.getConstructor(Arrays.stream(clazz.getRecordComponents()).map(RecordComponent::getType).toArray(Class[]::new)); ?
forget the stream
yes
getDeclaredConstructor
how can I fix this?
ye
I know this late asf. but isn't this bad practice? InventoryHolder was never designed to be used that way and could be deprecated at any moment.
No not deprecated
lemme now create an class array manually
Thats not the issue
You create a class which stores the world Id, chunkX and chunkY
can we do this in #1030635947093663754
thread?
The issue lies in the fact that you may encounter abnormal behavior as the implementation does not suppose api users to implement it as IH is just an api interface
ah okay, I seen choco say it could be removed before.
cool
like this is all i had to do on the surface, the rest is implemented
only have to find a way how to write preparedstatements with reflection 💀
We love reflection 😍
It most likely is
hello
hi
Yes, it has some advantages to the reflection API.
might wanna take a look at those
because the return value of "me.distruzionee.hubreforged.Main.getPlayerManager()" is null
and up to here
I got that
I don't understand what java doesn't understand, the value is not null
public PlayerManager getPlayerManager() { return playerManager; }
private PlayerManager playerManager;
when are you calling getplayermanager?
hopefully once your plugins onEnable has been called
i am learning how to make plugins, i wrote some code from a peer to peer course
Can we get more info? Is this just an IDE telling you its null or is an NullPointerException being thrown?
the IDE do not send me any error
why sendBlockChange is not working
i call it on PlayerinteractEvent
registered, other stuffs work
okay, so you need to make sure you set the value of playerManager when are you doing that?
?paste
is a class
not changing.
I would not say stupid, but you have not declared player
FREE JAVA LESSONS
tho you need to initialize your playerManager variable. When you declare it, it's always null
ohhh nothing srry
Can you show me where you set the value of playerManager?
i right click, with the shovel no block changing
in class constructor do
update blockstate or smth?
playerManager = new PlayerManager();
When you create the property you have to initialize it.
e.g
playerManager = new PlayerManager();
how
compare strings with ::equals
Not always, thats only if the property is final
k
or compare uuid itself with ::equals
will it fix that?
you are not getting it, im cancelling the normal shovel behaviour
dunno what a commandexception is
what
and im trying to change it to a gold block only for the player
idk
so im sending block change
why did i read that too
your receiver is null
Send a paste of the class that holds the playermanager
i already pointed you the line
i already have check for that
.
ye idk didnt look much at surrounding code
is this
uh
bruh...
show your class where you have
getPlayerManager() method
You're going to want to do this one tick later
The client is right clicking the block after you send the update, so the client requests an update for the server of the original block
yeah
If you do it one tick later it will update
i right click with shovel, no block changing 🤔 maybe just dont cancel anything
hehe
that was a weird question lol
ah changing it to a gold block?
doesn't exists
No, it works fine. Just Bukkit.getScheduler().runTask(plugin, () -> player.sendBlockChange(toLocation(), Material.GOLD_BLOCK));
this is gonna be a long evening
i'm wondering why not just change the block type in some event 👀
dunno much context
bro
you definitely have this method
but your variable is null
what is the class where you have this method
sorry bro
playerManager = new PlayerManager();
🤔 🤔
i try
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.
or take FREE JAVA LESSONS from me
<3
i think he will be scared when he hears your voice <3
Why
what HAHAHAH
idk i forgot how you sounded like
umm
Someone tryna learn Java
you probably talked to someone else
nah ike joined call too and then i heard kids screaming
or maybe that was my sister terrorising my brother
Russian accent makes it hard to tell age 
i don't have accent tho
Smoking at 15 makes you sound 45 by age 16