How to compare two Text object?

Text text=Text.of(“§5match”);

I set npc name on serverStart->entity.offer(Keys.DISPLAY_NAME, text);
and i save text variable reference in a field, then, I listen InteractEntityEvent to compare the text ref and the name of entity that be click.

targetEntity.getValue(Keys.DISPLAY_NAME).ifPresent(text_opt → {
LiteralText displayNameText = (LiteralText) text_opt.get();
if (text.equals(displayNameText){}

It’s weird, sometimes it’s equal, sometimes not.(maybe try restart server) WHY???(no error print)

I try Text#getConent(), one print “§5match”, another one print “match”.
try Text#toPlain(), same not equal.

Third try,

Text text=Text.of(“§5match”);
entity.offer(Keys.DISPLAY_NAME, text);
Text name=entity.getValue(Keys.DISPLAY_NAME);

text.toPlain() will equals name.getContent(),
This is only useful now, and I don’t know if it will fail at some point

Is it likely that the entity is getting unloaded and loaded again? Looking at the code, when an entity is loaded from NBT, it will call setCustomNameTag which is a legacy string. Sponge’s MixinEntity uses SpongeTexts.fromLegacy() which would result in a differently structured Text object. Using text.toPlain().equals(name.toPlain()) should work, unless you also need to compare formatting data.

In fact, I clean entity and add entity when server start everytime in order to prevent server crash cause entity can’t save normaly, Is this the wrong way?

If the entity could not be saved, that could be a bug. If you don’t know why it’s crashing maybe post the error log so we can investigate.

Sorry, it’s not sponge fault, it’s mine. Because i don’t want npc depend on the world(or map),I hate edit the lobby map, and i have a bad habit that is ctrl+c close server on linux.
Now, I use TextSerializers#LEGACY_FORMATTING_CODE and i think this problem is work out already.
Thanks for your answer!