-
-
Save aadnk/8a8a469027d863660aee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.comphenix.example; | |
import java.util.Random; | |
import org.bukkit.ChatColor; | |
import org.bukkit.command.Command; | |
import org.bukkit.command.CommandSender; | |
import org.bukkit.entity.Player; | |
import org.bukkit.event.Listener; | |
import org.bukkit.metadata.FixedMetadataValue; | |
import org.bukkit.metadata.MetadataValue; | |
import org.bukkit.metadata.Metadatable; | |
import org.bukkit.plugin.Plugin; | |
import org.bukkit.plugin.java.JavaPlugin; | |
public class MetadataStorage extends JavaPlugin implements Listener { | |
private static String[] ABILITIES = { "BLINK", "INVISIBILITY", "FIREBALL" }; | |
// Probably a good idea to use your namespace here | |
private static final String ABILITY_KEY = "com.comphenix.ability"; | |
private Random rnd = new Random(); | |
@Override | |
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { | |
if (sender instanceof Player) { | |
Player p = (Player) sender; | |
// Sub commands | |
if (args.length == 1) { | |
final String subCommand = args[0]; | |
if ("set".equalsIgnoreCase(subCommand)) { | |
String ability = ABILITIES[rnd.nextInt(ABILITIES.length)]; | |
setMetadata(p, ABILITY_KEY, ability); | |
sender.sendMessage(ChatColor.GOLD + "Setting ability to " + ability); | |
} else if ("get".equalsIgnoreCase(subCommand)) { | |
sender.sendMessage(ChatColor.GOLD + "Current ability is: " + getMetadata(p, ABILITY_KEY)); | |
} else { | |
sender.sendMessage(ChatColor.RED + "Unknown sub command: " + subCommand); | |
} | |
} else { | |
sender.sendMessage(ChatColor.RED + "Must specify one sub command"); | |
} | |
} | |
return true; | |
} | |
private void setMetadata(Metadatable target, String key, String value) { | |
target.setMetadata(key, new FixedMetadataValue(this, value)); | |
} | |
private String getMetadata(Metadatable source, String key) { | |
for (MetadataValue value : source.getMetadata(key)) { | |
Plugin owner = value.getOwningPlugin(); | |
// The previous plugin instance might have be collected | |
if (owner == null || owner.getName().equals(getName())) { | |
return value.asString(); | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment