Split a player's name and fill with color

Discussion in 'Plugin Development' started by FreakyPear5, Mar 25, 2020.

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

    FreakyPear5

    Hi,

    I'm doing a nickname plugin (as said in my last question :p) and I need to make a nickname that looks like this:
    upload_2020-3-25_11-43-36.png
    How do I split up a player's name and put the colors in it?
    I was thinking about using a for loop but I don't know what variables to use.
    Thanks,
    Freaky :D
     
  2. Offline

    KarimAKL

    @FreakyPear5 Something like this should work:
    Code:Java
    1. // The colors to change between
    2. // This way should allow for more than 2 as well, in case you want that later
    3. ChatColor colors = new ChatColor[] {ChatColor.AQUA, ChatColor.LIGHT_PURPLE};
    4.  
    5. // The name to color
    6. String name = "Cotton Candy";
    7.  
    8. // I split it at the spaces so that the spaces aren't colored
    9. // If i don't do this, it'll result in the "n" and "C" from "ton Can" being the same color
    10. String[] words = name.split(" ");
    11.  
    12. // A StringBuilder is better performance wise than String concatenation
    13. StringBuilder sb = new StringBuilder();
    14.  
    15. // We use this to keep track of the current color to use
    16. int colorIndex = 0;
    17.  
    18. // We loop the words in the name
    19. for (String word : words) {
    20.  
    21. // We loop the characters in the name
    22. for (char c : word.toCharArray()) {
    23.  
    24. // We add the color to the StringBuilder, then the character
    25. sb.append(colors[colorIndex]).append(c);
    26.  
    27. // We check if the colorIndex has reached the end of the colors array
    28. // If so, we make it start over
    29. if (colorIndex == colors.length - 1) color = 0;
    30. else color++;
    31. }
    32.  
    33. // Here we add the space that we removed earlier back again
    34. sb.append(" ");
    35. }
    36.  
    37. // Now we set the name to the colored version
    38. name = sb.toString();

    Although i haven't written anything in Java in some time now, so you could probably do it in some better way.
     
  3. Offline

    FreakyPear5

    @KarimAKL Ok thanks but what would I put after that to give the item its name? The setDisplayName(sb) doesn't work because its a stringbuilder

    EDIT: Sorry, ignore me!

    @KarimAKL I had a try of it, that doesn't work. On the if statement it says color is not defined, as for the else++ line. Switching them to colors instead of color makes them say they can't change int to boolean. Help?

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Mar 25, 2020
Thread Status:
Not open for further replies.

Share This Page