Hello! I was trying to create a mob which has two different textures: "red" and "black". It should be chosen randomly when the mob spawns and then never change. I had to find some way to save data about the variant of the mob when player go out from the game. I thought that using read/addAdditionalSaveData can help, but nothing has changed, it still doesn't remember what color each mob had. Did I something wrong? Here are methods in MyEntity class, related to the problem:
private final static EntityDataAccessor<String> DATA_VARIANT_NAME = SynchedEntityData.defineId(MyEntity.class, EntityDataSerializers.STRING);
//Entity variant is set in constructor
public MyEntity(EntityType<? extends Animal> pEntityType, Level pLevel) {
super(pEntityType, pLevel);
setMyEntityVariant(RandomMyEntityVariant());
}
@Override
protected void defineSynchedData() {
super.defineSynchedData();
this.entityData.define(DATA_VARIANT_NAME, RandomMyEntityVariant().getSerializedName());
}
public static enum MyEntityVariant implements StringRepresentable{
RED("red"),
BLACK("black");
private final String name;
private MyEntityVariant(String name){
this.name = name;
}
@Override
public String getSerializedName() {
return name;
}
public static MyEntityVariant byName(String pName) {
if (Objects.equals(pName, "black")){
return BLACK;
}
else return RED;
}
}
private MyEntityVariant RandomMyEntityVariant(){
switch (this.random.nextIntBetweenInclusive(1,2)){
case 1:
return MyEntityVariant.BLACK;
default:
return MyEntityVariant.RED;
}
}
public MyEntityVariant getMyEntityVariant(){
return MyEntityVariant.byName(this.entityData.get(DATA_VARIANT_NAME));
}
public void setMyEntityVariant(MyEntityVariant variant){
this.entityData.set(DATA_VARIANT_NAME,variant.getSerializedName());
}
@Override
public void addAdditionalSaveData(CompoundTag pCompound) {
super.addAdditionalSaveData(pCompound);
pCompound.putString("MyEntityVariant",this.getVariant().getSerializedName());
}
@Override
public void readAdditionalSaveData(CompoundTag pCompound) {
super.readAdditionalSaveData(pCompound);
this.setMyEntityVariant(MyEntityVariant.byName(pCompound.getString("MyEntityVariant")));
}
Maybe, I should call SetMyEntityVariant somewhere in another place?