How to support colored codes?

Discussion in 'Plugin Development' started by Monkey_Swag, Feb 28, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    Monkey_Swag

    Hey guys so I have a plugin similar to Citizens where you can make NPC's, etc. However, I want to make it so that when the player is going to name the NPC, it supports colored codes.

    This might be useful
    Code:java
    1. public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
    2. Player p = (Player) sender;
    3. if(!(sender instanceof Player)) {
    4. sender.sendMessage(ChatColor.RED + "Players Only!");
    5. } else if(cmd.getName().equalsIgnoreCase("sb")) {
    6. if(args.length == 0) {
    7. p.sendMessage(ChatColor.RED + "Error: Correct usage - /sb create <name> [Colorded codes are supported]");
    8. }else{ if(args[0].equalsIgnoreCase("create")){
    9. if(args.length == 1) {
    10. p.sendMessage(ChatColor.RED + "Please give your bot a name!");
    11. }else{
    12. args[1].replaceAll("&", "§"); //HERE IS WHERE I NEED HELP!
    13. Villager villager = (Villager) p.getWorld().spawnEntity(p.getLocation(), EntityType.VILLAGER);
    14. villager.setCustomName(args[1]);
    15. villager.setCustomNameVisible(true);
    16. villager.isAdult();
    17. villager.setMaxHealth(20.00);
    18. villager.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 999999999, 999999999));
    19.  
    20.  
    21.  
    22.  
    23.  
    24.  
    25. }
    26. }
    27.  
    28. }
    29.  
    30. }
    31. return true;
    32. }
     
  2. Offline

    Chinwe

    You need to keep in mind that methods like .replaceAll() as well as villager.isAdult() return the new String/a boolean respectively, which won't affect the original value, so set the villager name to ChatColor.translateAlternateColorCodes('&', args[1]) for a coloured name.

    Also, villager.setAdult() is a void method that will set the villager to an adult, instead of villager.isAdult(), which returns a boolean whether the villager is an adult or not - have a look in the docs :)
     
  3. Offline

    Maulss

    Use this:
    String string = ChatColor.translateAlternateColorCodes('&', args[1]);
     
  4. Offline

    FisheyLP

    just make it like that, its the easiest way:
    Code:Java
    1.  
    2. villager.setCustomName(args[1].replace("&","§"));
    3.  

    because you can use the § instead of & symbol for color codes, and with .replace(), it just replaces the & with a § :)
    EDIT: remove the args[1].replaceAll("&","§"); where you said you need help with.
     
  5. Offline

    Mr360zack

    Code:java
    1. String name = args[1]
    2. name = name.replaceAll("&", "§");
    3. then do .setName or whatever to name.
     
Thread Status:
Not open for further replies.

Share This Page