Как сохранить NBT-тег сущности (Fabric)?

Версия Minecraft
1.16.2
83
4
23
Суть такова: у меня есть существо, текстура которого зависит от его типа (не EntityType!).
При перезапуске мира текстура меняется, т.к. меняется тип существа, хотя тип должен сохранятся. Я переопределил writeCustomDataTag и readCustomDataTag, и при чтении тега, если тип равен null, он выбирается случайно.
Почему тип существа не сохраняется?
Сначала я пришел к одному выводу - я инициализирую тип в конструкторе. Но в таком случае тип все равно должен считываться, ибо методы writeCustomDataTag и readCustomDataTag вызываются после конструктора
EEEfvgel.jpeg

Я поменял кое-что, но игра теперь бросает NPE при рендере существа (т.к. текстуры нет, ведь типа тоже нет)
В итоге это выглядит вот так:

Java:
public class HumanEntity extends PassiveEntity implements Npc {
    private Type type;

    public HumanEntity(World world) {
        super(Entities.ENTITY_HUMAN, world);
        //this.type = initType(); 
        initGoals();
    }

    public HumanEntity(EntityType<Entity> entityEntityType, World world) {
        super(Entities.ENTITY_HUMAN, world);
        //this.type = initType();
        initGoals();
    }

    private Type initType() {
        return Type.values()[random.nextInt(Type.values().length)];
    }

    public Type getHumanType() {
        return this.type;
    }

    @Override
    public void writeCustomDataToTag(CompoundTag tag) {
        super.writeCustomDataToTag(tag);
        if (type == null)
            this.type = initType();
        tag.putString("HumanType", this.type.toString());
    }

    @Override
    public void readCustomDataFromTag(CompoundTag tag) {
        super.readCustomDataFromTag(tag);
        String type = tag.getString("HumanType");
        if (type == null)
            this.type = initType();
    }

    public enum Type {
        ALEX("textures/entity/alex.png"),
        STEVE("textures/entity/steve.png");

        private final Identifier identifier;
        Type(String texture) {
            this.identifier = new Identifier(MOD_ID, texture);
        }
        public Identifier getTexture() {
            return this.identifier;
        }
    }

}
 
Последнее редактирование:
83
4
23
Короче, дело не в тегах, они оказывается прекрасно сохраняются и читаются. Как мне тогда отображать текстуру, зависящую от переменной, чтобы эта переменная сохранялась в тег?

HumanEntity.java:
public class HumanEntity extends PassiveEntity implements Npc {
    private Type type;

    public HumanEntity(EntityType<Entity> entityEntityType, World world) {
        super(Entities.ENTITY_HUMAN, world);
        ((MobNavigation)this.getNavigation()).setCanPathThroughDoors(true);
        this.getNavigation().setCanSwim(true);
        initGoals();
    }

    public Type initType() {
        return Type.values()[random.nextInt(Type.values().length)];
    }

    public Type getHumanType() {
        return this.type;
    }

    @Override
    public void writeCustomDataToTag(CompoundTag tag) {
        super.writeCustomDataToTag(tag);
        tag.put("Inventory", this.inventory.getTags());
        tag.putString("HumanType", this.type.toString().toUpperCase());
    }

    @Override
    public void readCustomDataFromTag(CompoundTag tag) {
        super.readCustomDataFromTag(tag);
        this.inventory.readTags(tag.getList("Inventory", 10));
        if (tag.contains("HumanType"))
            this.type = Type.valueOf(tag.getString("HumanType").toUpperCase());
        else
            this.type = initType();

    }

    public enum Type {
        ALEX("textures/entity/alex.png"),
        STEVE("textures/entity/steve.png");

        private final Identifier identifier;
        Type(String texture) {
            this.identifier = new Identifier(MOD_ID, texture);
        }
        public Identifier getTexture() {
            return this.identifier;
        }
    }


HumanEntityRenderer.java:
public class HumanEntityRenderer extends MobEntityRenderer<HumanEntity, HumanEntityModel<HumanEntity>> {

    public HumanEntityRenderer(EntityRenderDispatcher entityRenderDispatcher, HumanEntityModel<HumanEntity> entityModel) {
        super(entityRenderDispatcher, entityModel, 1.0F);
        this.addFeature(new HeldItemFeatureRenderer(this));
        this.addFeature(new ArmorFeatureRenderer(this, new BipedEntityModel(0.5F), new BipedEntityModel(1.0F)));
    }

    /**
    * Этот метод отвечает за отображаемую текстуру
    */
    @Override
    public Identifier getTexture(HumanEntity entity) {
        HumanEntity.Type type = entity.getHumanType();
        if (type == null) // Почему то тип всегда null, и из-за этого текстуры быстро меняются
            type = entity.initType();
        return type.getTexture();
    }
}


Java:
@Environment(EnvType.CLIENT)
public class ModClient implements ClientModInitializer {
    @Override
    public void onInitializeClient() {
        EntityRendererRegistry.INSTANCE.register(Entities.ENTITY_HUMAN,
                                                 ((entityRenderDispatcher, context) ->
                                                  new HumanEntityRenderer(entityRenderDispatcher,
                                                  new HumanEntityModel<HumanEntity>(0.5F))));
    }
}
 

tox1cozZ

aka Agravaine
8,454
598
2,890
А ничего что у тебя метод initType просто возвращает значение, а не устанавливает его переменной type?
А еще нужно это значение слать клиенту при спавне моба. Хз как в ваших 1.16, но на 1.12.2 есть интерфейс IAdditionalSpawnData, который расширяешь в своем мобе и можно легко синхронизировать данные при спавне.
 
3,005
192
592
Сверху