Jump to content

Recommended Posts

Posted

That should work, yes.

Okay, but I've been getting this error:

 

Failed to save chunk
net.minecraft.util.ReportedException: Saving entity NBT
at net.minecraft.entity.Entity.writeToNBT(Entity.java:1877) ~[Entity.class:?]
at net.minecraft.entity.Entity.writeToNBTOptional(Entity.java:1760) ~[Entity.class:?]
at net.minecraft.world.chunk.storage.AnvilChunkLoader.writeChunkToNBT(AnvilChunkLoader.java:394) ~[AnvilChunkLoader.class:?]
at net.minecraft.world.chunk.storage.AnvilChunkLoader.saveChunk(AnvilChunkLoader.java:191) [AnvilChunkLoader.class:?]
at net.minecraft.world.gen.ChunkProviderServer.saveChunkData(ChunkProviderServer.java:209) [ChunkProviderServer.class:?]
at net.minecraft.world.gen.ChunkProviderServer.saveChunks(ChunkProviderServer.java:237) [ChunkProviderServer.class:?]
at net.minecraft.world.WorldServer.saveAllChunks(WorldServer.java:1065) [WorldServer.class:?]
at net.minecraft.server.MinecraftServer.saveAllWorlds(MinecraftServer.java:425) [MinecraftServer.class:?]
at net.minecraft.server.integrated.IntegratedServer.saveAllWorlds(IntegratedServer.java:238) [integratedServer.class:?]
at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:141) [integratedServer.class:?]
at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:547) [MinecraftServer.class:?]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_111]
Caused by: java.lang.IllegalArgumentException: Empty string not allowed
at net.minecraft.nbt.NBTTagString.<init>(NBTTagString.java:23) ~[NBTTagString.class:?]
at net.minecraft.nbt.NBTTagCompound.setString(NBTTagCompound.java:158) ~[NBTTagCompound.class:?]
at orangeVillager61.ImprovedVillagers.Entities.VillagerStorages.writeNBT(VillagerStorages.java:25) ~[VillagerStorages.class:?]
at orangeVillager61.ImprovedVillagers.Entities.VillagerStorages.writeNBT(VillagerStorages.java:1) ~[VillagerStorages.class:?]
at orangeVillager61.ImprovedVillagers.Entities.VillagerProvider.serializeNBT(VillagerProvider.java:53) ~[VillagerProvider.class:?]
at net.minecraftforge.common.capabilities.CapabilityDispatcher.serializeNBT(CapabilityDispatcher.java:123) ~[CapabilityDispatcher.class:?]
at net.minecraft.entity.Entity.writeToNBT(Entity.java:1846) ~[Entity.class:?]
... 11 more

Posted

You can't create an

NBTTagString

with a

null

value, so you can't call

NBTTagCompound#setString

with a

null

value.

 

Only call

NBTTagCompound#setString

if the name value isn't

null

.

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Posted

Okay, also, do I need to do anything to the render the villagers other than

 

		ResourceLocation resourceLocation1 = new ResourceLocation("iv", "villager");
	EntityRegistry.registerModEntity(resourceLocation1, IvVillager.class, "IvVillager", 0, Iv.instance, 32, 1, true);

Posted

EntityRegistry.registerModEntity

isn't really related to rendering, but it is required to register your entity class using it.

 

If you don't explicitly register a

Render

for your entity class, Minecraft will use the one for the super class.

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Posted

EntityRegistry.registerModEntity

isn't really related to rendering, but it is required to register your entity class using it.

 

If you don't explicitly register a

Render

for your entity class, Minecraft will use the one for the super class.

Alright, and how do I know if it is using the Villager renderer?

Posted

Okay, I seem to have fixed most bugs but I have two major issues, firstly when overriding a villager, there's a around 50% chance it doesn't override and the original entity turns into a strange thing that looks like a villager but doesn't behave like an entity and I can go through it and doesn't obey the las of gravity.

 

Also, the overrided villager doesn't gain a name until I reload the game.

 

public class OverrideVillagers {
@SubscribeEvent
public void entityJoinedWorldEventHandler(EntityJoinWorldEvent event)
{
	if (event.getEntity().getClass() == EntityVillager.class && Config.overwriteOriginalVillagers == 0)
	{
		event.getEntity().setDead();
		doOverwriteVillager(event, (EntityVillager) event.getEntity());
	}
}

private void doOverwriteVillager(EntityJoinWorldEvent event, EntityVillager entity) 
{
	if (entity.getProfession() >= 0 && entity.getProfession() <= 4)
	{
		IvVillager entityVillager = new IvVillager(entity.getWorld(), entity.getProfession());
		entityVillager.setGrowingAge(entity.getGrowingAge());
		entityVillager.onInitialSpawn(event.getWorld().getDifficultyForLocation(new BlockPos(entity)), (IEntityLivingData)null);
		entityVillager.setLocationAndAngles(entity.posX, entity.posY, entity.posZ, 0.0F, 0.0F);
		event.getWorld().setEntityState(entityVillager, (byte)12); 
		event.getWorld().spawnEntity(entityVillager); 

	}
}
}

Posted
2 hours ago, diesieben07 said:

Post your villager class.

public class IvVillager extends EntityVillager{
	
	protected Village villageObj; 
	public String name;
	public int Gender;
    protected boolean isWillingToMate;
    protected int wealth;
    private MerchantRecipeList buyingList;
    private String lastBuyingPlayer;
    private int careerId;
    private int careerLevel;
    private boolean isLookingForHome;
    private boolean areAdditionalTasksSet;
    private final InventoryBasic villagerInventory;
    Random r = new Random();
    /** A multi-dimensional array mapping the various professions, careers and career levels that a Villager may offer */
	protected String[] male_list = {"Bob", "Joseph", "Aaron", "Philp", "Adam", "Paul", "Donald", "Ryan", 
									"Mark", "Brian", "Robert", "Willam", "Harold", "Anthony", "Julius", 
									"Mathew", "Tyler", "Noah", "Patrick", "Caden", "Michael", "Jeffery",
									"James", "John", "Thomas", "Otto", "Bill", "Sheldon", "Leonard", 
									"Howard", "Carter", "Theodore", "Herbert"};
	protected String[] female_list = {"Karen", "Lessie", "Kayla", "Brianna", "Isabella", "Elizabeth",
									  "Kira", "Jadzia", "Abigail", "Chloe", "Olivia", "Sophia", "Emily", 
									  "Charlotte", "Amelia", "Maria", "Daria", "Sarah", "Theodora",
									  "Tia", "Jennifer", "Anglica", "Denna", "Tasha", "Catherine", "Lily",
									  "Amy", "Penny", "Julina", "Audrey", "Avery"};
	
	public IvVillager(World world) {
		super(world);
        this.villagerInventory = new InventoryBasic("Items", false, 8);
	}
	public IvVillager(World world, int professionId) {
		super(world, professionId);
	    this.setProfession(professionId);
        this.villagerInventory = new InventoryBasic("Items", false, 8);
	}
	public InventoryBasic getVillagerInventory()
    {
        return this.villagerInventory;
    }
	 @Override
	 public void writeEntityToNBT(NBTTagCompound compound)
	    {
	        super.writeEntityToNBT(compound);
	        compound.setInteger("Profession", this.getProfession());
	        compound.setString("ProfessionName", this.getProfessionForge().getRegistryName().toString());
	        compound.setInteger("Riches", this.wealth);
	        compound.setInteger("Career", this.careerId);
	        compound.setInteger("CareerLevel", this.careerLevel);
	        compound.setBoolean("Willing", this.isWillingToMate);

	        if (this.buyingList != null)
	        {
	            compound.setTag("Offers", this.buyingList.getRecipiesAsTags());
	        }

	        NBTTagList nbttaglist = new NBTTagList();

	        for (int i = 0; i < this.getVillagerInventory().getSizeInventory(); ++i)
	        {
	            ItemStack itemstack = this.villagerInventory.getStackInSlot(i);

	            if (!itemstack.isEmpty())
	            {
	                nbttaglist.appendTag(itemstack.writeToNBT(new NBTTagCompound()));
	            }
	        }

	        compound.setTag("Inventory", nbttaglist);
	        if (world.isRemote == false){
	        	IVillagerStorage villagerN = this.getCapability(VillagerProvider.VIL_CAP, null);
	        	villagerN.setGender(this.Gender);
	        	villagerN.setName(this.name);
	        }
	        
	    }
	 @Override
	 public void readEntityFromNBT(NBTTagCompound compound){
		 super.writeEntityToNBT(compound);
		 if (world.isRemote == false){
	         IVillagerStorage villagerN = this.getCapability(VillagerProvider.VIL_CAP, null);
			 this.name = villagerN.getName();
			 this.Gender = villagerN.getGender();
			 this.setCustomNameTag(this.name);
		 }
		 this.setProfession(compound.getInteger("Profession"));
	        if (compound.hasKey("ProfessionName"))
	        {
	            net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession p =
	                net.minecraftforge.fml.common.registry.VillagerRegistry.instance().getRegistry().getValue(new net.minecraft.util.ResourceLocation(compound.getString("ProfessionName")));
	            if (p == null)
	                p = net.minecraftforge.fml.common.registry.VillagerRegistry.instance().getRegistry().getValue(new net.minecraft.util.ResourceLocation("minecraft:farmer"));
	            this.setProfession(p);
	        }
	        this.wealth = compound.getInteger("Riches");
	        this.careerId = compound.getInteger("Career");
	        this.careerLevel = compound.getInteger("CareerLevel");
	        this.isWillingToMate = compound.getBoolean("Willing");

	        if (compound.hasKey("Offers", 10))
	        {
	            NBTTagCompound nbttagcompound = compound.getCompoundTag("Offers");
	            this.buyingList = new MerchantRecipeList(nbttagcompound);
	        }

	        NBTTagList nbttaglist = compound.getTagList("Inventory", 10);

	        for (int i = 0; i < nbttaglist.tagCount(); ++i)
	        {
	            ItemStack itemstack = new ItemStack(nbttaglist.getCompoundTagAt(i));

	            if (!itemstack.isEmpty())
	            {
	                this.villagerInventory.addItem(itemstack);
	            }
	        }

	        this.setCanPickUpLoot(true);
	        this.setAdditionalAItasks();
		 
	 }
	 private void populateBuyingList()
	    {
	        if (this.careerId != 0 && this.careerLevel != 0)
	        {
	            ++this.careerLevel;
	        }
	        else
	        {
	            this.careerId = this.getProfessionForge().getRandomCareer(this.rand) + 1;
	            this.careerLevel = 1;
	        }

	        if (this.buyingList == null)
	        {
	            this.buyingList = new MerchantRecipeList();
	        }

	        int i = this.careerId - 1;
	        int j = this.careerLevel - 1;
	        java.util.List<EntityVillager.ITradeList> trades = this.getProfessionForge().getCareer(i).getTrades(j);

	        if (trades != null)
	        {
	            for (EntityVillager.ITradeList entityvillager$itradelist : trades)
	            {
	                entityvillager$itradelist.addMerchantRecipe(this, this.buyingList, this.rand);
	            }
	        }
	    }
    }

}

 

Posted (edited)
On 2/10/2017 at 1:36 PM, diesieben07 said:

Yes...

Alright, but this causes the villager to be removed...

public class IvVillager extends EntityVillager{
	
	public IvVillager(World world) {
		super(world);
        this.villagerInventory = new InventoryBasic("Items", false, 20);
	}
	public IvVillager(World world, int professionId) {
		super(world, professionId);
	    this.setProfession(professionId);
        this.villagerInventory = new InventoryBasic("Items", false, 20);
	}
	public InventoryBasic getVillagerInventory()
    {
        return this.villagerInventory;
    }
	@Override
	protected void entityInit()
    {
		super.entityInit();
		this.getDataManager().register(Gender, Integer.valueOf(0));
        this.setGender();
		this.getDataManager().register(Name, String.valueOf("None"));
		this.setName();
    }
	@Override
	protected void initEntityAI()
    {
        this.tasks.addTask(0, new EntityAISwimming(this));
        this.tasks.addTask(1, new EntityAIAvoidEntity(this, EntityZombie.class, 8.0F, 0.6D, 0.6D));
        this.tasks.addTask(1, new EntityAIAvoidEntity(this, EntityEvoker.class, 12.0F, 0.8D, 0.8D));
        this.tasks.addTask(1, new EntityAIAvoidEntity(this, EntityVindicator.class, 8.0F, 0.8D, 0.8D));
        this.tasks.addTask(1, new EntityAIAvoidEntity(this, EntityVex.class, 8.0F, 0.6D, 0.6D));
        this.tasks.addTask(1, new EntityAITradePlayer(this));
        this.tasks.addTask(2, new EntityAILookAtTradePlayer(this));
        this.tasks.addTask(2, new EntityAIMoveIndoors(this));
        this.tasks.addTask(3, new EntityAIRestrictOpenDoor(this));
        this.tasks.addTask(4, new EntityAITempt(this, 1.25D, Items.EMERALD, false));
        this.tasks.addTask(4, new EntityAIOpenDoor(this, true));
        this.tasks.addTask(5, new EntityAIMoveTowardsRestriction(this, 0.6D));
        this.tasks.addTask(6, new VilsPerDoor(this));
        this.tasks.addTask(7, new EntityAIFollowGolem(this));
        this.tasks.addTask(9, new EntityAIWatchClosest2(this, EntityPlayer.class, 3.0F, 1.0F));
        this.tasks.addTask(9, new EntityAIVillagerInteract(this));
        this.tasks.addTask(9, new EntityAIWanderAvoidWater(this, 0.6D));
        this.tasks.addTask(10, new EntityAIWatchClosest(this, EntityLiving.class, 8.0F));
    }
	public int getGender()
    {
        return ((Integer)this.getDataManager().get(Gender)).intValue();
    }
	public void setGender()
	{
		IVillagerStorage villagerN = this.getCapability(VillagerProvider.VIL_CAP, null);
		if (this.gender == 0 || this.gender == 1){
			villagerN.setGender(this.gender);
		}
		this.getDataManager().set(Gender, Integer.valueOf(this.gender));
	}
	public String getName()
	{
        return ((String)this.getDataManager().get(Name));
	}
	public void setName()
	{
		IVillagerStorage villagerN = this.getCapability(VillagerProvider.VIL_CAP, null);
		if (this.name != null){
			villagerN.setName(this.name);
		}
		this.getDataManager().set(Name, String.valueOf(this.name));
	}
	private void setAdditionalAItasks()
    {
        if (!this.areAdditionalTasksSet)
        {
            this.areAdditionalTasksSet = true;

            if (this.isChild())
            {
                this.tasks.addTask(8, new EntityAIPlay(this, 0.32D));
            }
            else if (this.getProfession() == 0)
            {
                this.tasks.addTask(6, new EntityAIHarvestFarmland(this, 0.6D));
            }
        }
    }
	 @Override
	 public void writeEntityToNBT(NBTTagCompound compound)
	    {
	        super.writeEntityToNBT(compound);
	        compound.setInteger("Profession", this.getProfession());
	        compound.setString("ProfessionName", this.getProfessionForge().getRegistryName().toString());
	        compound.setInteger("Riches", this.wealth);
	        compound.setInteger("Career", this.careerId);
	        compound.setInteger("CareerLevel", this.careerLevel);
	        compound.setBoolean("Willing", this.isWillingToMate);

	        if (this.buyingList != null)
	        {
	            compound.setTag("Offers", this.buyingList.getRecipiesAsTags());
	        }

	        NBTTagList nbttaglist = new NBTTagList();

	        for (int i = 0; i < this.getVillagerInventory().getSizeInventory(); ++i)
	        {
	            ItemStack itemstack = this.villagerInventory.getStackInSlot(i);

	            if (!itemstack.isEmpty())
	            {
	                nbttaglist.appendTag(itemstack.writeToNBT(new NBTTagCompound()));
	            }
	        }

	        compound.setTag("Inventory", nbttaglist);
	        if (world.isRemote == false){
	        	this.setGender();
	        	this.setName();
	        }
	        
	    }
	 @Override
	 public void readEntityFromNBT(NBTTagCompound compound){
		 super.writeEntityToNBT(compound);
		 if (world.isRemote == false){
			 this.getGender();
			 this.getName();
			 this.setCustomNameTag(this.getName());
		 }
		 this.setProfession(compound.getInteger("Profession"));
	        if (compound.hasKey("ProfessionName"))
	        {
	            net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession p =
	                net.minecraftforge.fml.common.registry.VillagerRegistry.instance().getRegistry().getValue(new net.minecraft.util.ResourceLocation(compound.getString("ProfessionName")));
	            if (p == null)
	                p = net.minecraftforge.fml.common.registry.VillagerRegistry.instance().getRegistry().getValue(new net.minecraft.util.ResourceLocation("minecraft:farmer"));
	            this.setProfession(p);
	        }
	        this.wealth = compound.getInteger("Riches");
	        this.careerId = compound.getInteger("Career");
	        this.careerLevel = compound.getInteger("CareerLevel");
	        this.isWillingToMate = compound.getBoolean("Willing");

	        if (compound.hasKey("Offers", 10))
	        {
	            NBTTagCompound nbttagcompound = compound.getCompoundTag("Offers");
	            this.buyingList = new MerchantRecipeList(nbttagcompound);
	        }

	        NBTTagList nbttaglist = compound.getTagList("Inventory", 10);

	        for (int i = 0; i < nbttaglist.tagCount(); ++i)
	        {
	            ItemStack itemstack = new ItemStack(nbttaglist.getCompoundTagAt(i));

	            if (!itemstack.isEmpty())
	            {
	                this.villagerInventory.addItem(itemstack);
	            }
	        }

	        this.setCanPickUpLoot(true);
	        this.setAdditionalAItasks();
		 
	 }
	 private void populateBuyingList()
	    {
	        if (this.careerId != 0 && this.careerLevel != 0)
	        {
	            ++this.careerLevel;
	        }
	        else
	        {
	            this.careerId = this.getProfessionForge().getRandomCareer(this.rand) + 1;
	            this.careerLevel = 1;
	        }

	        if (this.buyingList == null)
	        {
	            this.buyingList = new MerchantRecipeList();
	        }

	        int i = this.careerId - 1;
	        int j = this.careerLevel - 1;
	        java.util.List<EntityVillager.ITradeList> trades = this.getProfessionForge().getCareer(i).getTrades(j);

	        if (trades != null)
	        {
	            for (EntityVillager.ITradeList entityvillager$itradelist : trades)
	            {
	                entityvillager$itradelist.addMerchantRecipe(this, this.buyingList, this.rand);
	            }
	        }
	    }
	 @Override
	 public boolean processInteract(EntityPlayer player, EnumHand hand){
		if (world.isRemote == false){
			BlockPos blockpos = new BlockPos(this);
			this.villageObj = this.world.getVillageCollection().getNearestVillage(blockpos, 32);

		}
        ItemStack itemstack = player.getHeldItem(hand);
        if (itemstack.getItem() == IvItems.thieving_nose && !this.isChild()){
        	itemstack.damageItem(1, player);
        	this.setHealth(this.getHealth() - 2);
        	this.playHurtSound(getLastDamageSource());
        	if (rand.nextInt(10) + 1 < 6){
        		
        	}
        	if (rand.nextInt(10) + 1 < 9 && rand.nextInt(10) + 1  > 5){
        		this.entityDropItem(new ItemStack(Items.EMERALD, r.nextInt(2) + 1), 0);
        	}
        	if (rand.nextInt(10) + 1 < 10 && rand.nextInt(10) + 1  > 8){
        		this.entityDropItem(new ItemStack(Items.EMERALD, r.nextInt(2) + 1), 0);
        	}
        	if (world.isRemote == false){
        	if (this.villageObj != null)
	            {
	        		this.villageObj.modifyPlayerReputation(player.getName(), -2);
	            }
        	}
            return true;
        }
        else if (!this.holdingSpawnEggOfClass(itemstack, this.getClass()) && this.isEntityAlive() && !this.isTrading() && !this.isChild())
        {
            if (this.buyingList == null)
            {
                this.populateBuyingList();
            }

            if (hand == EnumHand.MAIN_HAND)
            {
                player.addStat(StatList.TALKED_TO_VILLAGER);
            }

            if (!this.world.isRemote && !this.buyingList.isEmpty())
            {
                this.setCustomer(player);
                player.displayVillagerTradeGui(this);
            }
            else if (this.buyingList.isEmpty())
            {
                return super.processInteract(player, hand);
            }

            return true;
        }
        else
        {
            return super.processInteract(player, hand);
        }
    }

}

 

Edited by OrangeVillager61
syntax hightlighting
Posted
On 2/11/2017 at 4:45 PM, diesieben07 said:

What do you mean by removed? And do you seriously expect me (or anyone) to know the answer to such a broad question without even being able to run the code?

Okay, sorry. I mean that when I spawn a villager with the code above, the villagers gets removed and has this a NullPointerException:

 

Quote

[21:31:43] [Server thread/FATAL]: Error executing task
java.util.concurrent.ExecutionException: java.lang.NullPointerException
    at java.util.concurrent.FutureTask.report(Unknown Source) ~[?:1.8.0_121]
    at java.util.concurrent.FutureTask.get(Unknown Source) ~[?:1.8.0_121]
    at net.minecraft.util.Util.runTask(Util.java:27) [Util.class:?]
    at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:753) [MinecraftServer.class:?]
    at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:698) [MinecraftServer.class:?]
    at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:156) [IntegratedServer.class:?]
    at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:547) [MinecraftServer.class:?]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_121]
Caused by: java.lang.NullPointerException
    at orangeVillager61.ImprovedVillagers.Entities.IvVillager.setGender(IvVillager.java:126) ~[IvVillager.class:?]
    at orangeVillager61.ImprovedVillagers.Entities.IvVillager.entityInit(IvVillager.java:92) ~[IvVillager.class:?]
    at net.minecraft.entity.Entity.<init>(Entity.java:252) ~[Entity.class:?]
    at net.minecraft.entity.EntityLivingBase.<init>(EntityLivingBase.java:197) ~[EntityLivingBase.class:?]
    at net.minecraft.entity.EntityLiving.<init>(EntityLiving.java:101) ~[EntityLiving.class:?]
    at net.minecraft.entity.EntityCreature.<init>(EntityCreature.java:22) ~[EntityCreature.class:?]
    at net.minecraft.entity.EntityAgeable.<init>(EntityAgeable.java:27) ~[EntityAgeable.class:?]
    at net.minecraft.entity.passive.EntityVillager.<init>(EntityVillager.java:130) ~[EntityVillager.class:?]
    at orangeVillager61.ImprovedVillagers.Entities.IvVillager.<init>(IvVillager.java:79) ~[IvVillager.class:?]
    at orangeVillager61.ImprovedVillagers.OverrideVillagers.doOverwriteVillager(OverrideVillagers.java:27) ~[OverrideVillagers.class:?]
    at orangeVillager61.ImprovedVillagers.OverrideVillagers.entityJoinedWorldEventHandler(OverrideVillagers.java:19) ~[OverrideVillagers.class:?]
    at net.minecraftforge.fml.common.eventhandler.ASMEventHandler_7_OverrideVillagers_entityJoinedWorldEventHandler_EntityJoinWorldEvent.invoke(.dynamic) ~[?:?]
    at net.minecraftforge.fml.common.eventhandler.ASMEventHandler.invoke(ASMEventHandler.java:90) ~[ASMEventHandler.class:?]
    at net.minecraftforge.fml.common.eventhandler.EventBus.post(EventBus.java:185) ~[EventBus.class:?]
    at net.minecraft.world.World.spawnEntity(World.java:1291) ~[World.class:?]
    at net.minecraft.world.WorldServer.spawnEntity(WorldServer.java:1125) ~[WorldServer.class:?]
    at net.minecraft.item.ItemMonsterPlacer.spawnCreature(ItemMonsterPlacer.java:251) ~[ItemMonsterPlacer.class:?]
    at net.minecraft.item.ItemMonsterPlacer.onItemUse(ItemMonsterPlacer.java:101) ~[ItemMonsterPlacer.class:?]
    at net.minecraftforge.common.ForgeHooks.onPlaceItemIntoWorld(ForgeHooks.java:812) ~[ForgeHooks.class:?]
    at net.minecraft.item.ItemStack.onItemUse(ItemStack.java:179) ~[ItemStack.class:?]
    at net.minecraft.server.management.PlayerInteractionManager.processRightClickBlock(PlayerInteractionManager.java:506) ~[PlayerInteractionManager.class:?]
    at net.minecraft.network.NetHandlerPlayServer.processTryUseItemOnBlock(NetHandlerPlayServer.java:701) ~[NetHandlerPlayServer.class:?]
    at net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock.processPacket(CPacketPlayerTryUseItemOnBlock.java:68) ~[CPacketPlayerTryUseItemOnBlock.class:?]
    at net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock.processPacket(CPacketPlayerTryUseItemOnBlock.java:13) ~[CPacketPlayerTryUseItemOnBlock.class:?]
    at net.minecraft.network.PacketThreadUtil$1.run(PacketThreadUtil.java:15) ~[PacketThreadUtil$1.class:?]
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) ~[?:1.8.0_121]
    at java.util.concurrent.FutureTask.run(Unknown Source) ~[?:1.8.0_121]
    at net.minecraft.util.Util.runTask(Util.java:26) ~[Util.class:?]
    ... 5 more
[21:31:43] [Server thread/ERROR] [FML]: Exception caught during firing event net.minecraftforge.event.entity.EntityJoinWorldEvent@2a3b1ab:
java.lang.NullPointerException
    at orangeVillager61.ImprovedVillagers.Entities.IvVillager.setGender(IvVillager.java:126) ~[IvVillager.class:?]
    at orangeVillager61.ImprovedVillagers.Entities.IvVillager.entityInit(IvVillager.java:92) ~[IvVillager.class:?]
    at net.minecraft.entity.Entity.<init>(Entity.java:252) ~[Entity.class:?]
    at net.minecraft.entity.EntityLivingBase.<init>(EntityLivingBase.java:197) ~[EntityLivingBase.class:?]
    at net.minecraft.entity.EntityLiving.<init>(EntityLiving.java:101) ~[EntityLiving.class:?]
    at net.minecraft.entity.EntityCreature.<init>(EntityCreature.java:22) ~[EntityCreature.class:?]
    at net.minecraft.entity.EntityAgeable.<init>(EntityAgeable.java:27) ~[EntityAgeable.class:?]
    at net.minecraft.entity.passive.EntityVillager.<init>(EntityVillager.java:130) ~[EntityVillager.class:?]
    at orangeVillager61.ImprovedVillagers.Entities.IvVillager.<init>(IvVillager.java:79) ~[IvVillager.class:?]
    at orangeVillager61.ImprovedVillagers.OverrideVillagers.doOverwriteVillager(OverrideVillagers.java:27) ~[OverrideVillagers.class:?]
    at orangeVillager61.ImprovedVillagers.OverrideVillagers.entityJoinedWorldEventHandler(OverrideVillagers.java:19) ~[OverrideVillagers.class:?]
    at net.minecraftforge.fml.common.eventhandler.ASMEventHandler_7_OverrideVillagers_entityJoinedWorldEventHandler_EntityJoinWorldEvent.invoke(.dynamic) ~[?:?]
    at net.minecraftforge.fml.common.eventhandler.ASMEventHandler.invoke(ASMEventHandler.java:90) ~[ASMEventHandler.class:?]
    at net.minecraftforge.fml.common.eventhandler.EventBus.post(EventBus.java:185) [EventBus.class:?]
    at net.minecraft.world.World.spawnEntity(World.java:1291) [World.class:?]
    at net.minecraft.world.WorldServer.spawnEntity(WorldServer.java:1125) [WorldServer.class:?]
    at net.minecraft.item.ItemMonsterPlacer.spawnCreature(ItemMonsterPlacer.java:251) [ItemMonsterPlacer.class:?]
    at net.minecraft.item.ItemMonsterPlacer.onItemUse(ItemMonsterPlacer.java:101) [ItemMonsterPlacer.class:?]
    at net.minecraftforge.common.ForgeHooks.onPlaceItemIntoWorld(ForgeHooks.java:812) [ForgeHooks.class:?]
    at net.minecraft.item.ItemStack.onItemUse(ItemStack.java:179) [ItemStack.class:?]
    at net.minecraft.server.management.PlayerInteractionManager.processRightClickBlock(PlayerInteractionManager.java:506) [PlayerInteractionManager.class:?]
    at net.minecraft.network.NetHandlerPlayServer.processTryUseItemOnBlock(NetHandlerPlayServer.java:701) [NetHandlerPlayServer.class:?]
    at net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock.processPacket(CPacketPlayerTryUseItemOnBlock.java:68) [CPacketPlayerTryUseItemOnBlock.class:?]
    at net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock.processPacket(CPacketPlayerTryUseItemOnBlock.java:13) [CPacketPlayerTryUseItemOnBlock.class:?]
    at net.minecraft.network.PacketThreadUtil$1.run(PacketThreadUtil.java:15) [PacketThreadUtil$1.class:?]
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:1.8.0_121]
    at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_121]
    at net.minecraft.util.Util.runTask(Util.java:26) [Util.class:?]
    at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:753) [MinecraftServer.class:?]
    at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:698) [MinecraftServer.class:?]
    at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:156) [IntegratedServer.class:?]
    at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:547) [MinecraftServer.class:?]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_121]

 

 

Posted
6 minutes ago, diesieben07 said:

You have duplication of data, you store the gender both in the data manager and the capability. Pick one.

And then use the debugger to find out what is null on that line and why.

I would normally use a capability but is it possible to use a capability and have the game show the name without reloading?

Posted (edited)
On 2/12/2017 at 0:33 PM, OrangeVillager61 said:

Caused by: java.lang.NullPointerException
    at orangeVillager61.ImprovedVillagers.Entities.IvVillager.setGender(IvVillager.java:126)

Did you know that you can click on the "126" to go directly to the problem line? Have you set a breakpoint there? Have you used the debugger at all?

 

As my signature used to say (before the site "upgrade", we had signatures), the debugger is an essential development tool. No matter how weird and mysterious it seems, you must pierce the barrier to its use. Just dive in and start reading its help pages. Once you discover its stepping and its runtime variable examination, you'll wonder how you ever lived without it.

Edited by jeffryfisher
What happened to my signature?

The debugger is a powerful and necessary tool in any IDE, so learn how to use it. You'll be able to tell us more and get better help here if you investigate your runtime problems in the debugger before posting.

Posted

We still have signatures, just that per-user-settings they are turned off by default.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted

Okay, so I fixed much of my issues, but the game only displays "None" instead of a name. The game does correctly set names in the WriteNBT but those names don't seem to persist in reloads or actually show. I determined this using printlns.

 

public class IvVillager extends EntityVillager{
	
	protected Village villageObj; 
	public String name;
	public int gender;
    protected boolean isWillingToMate;
    protected int wealth;
    protected MerchantRecipeList buyingList;
    protected static final DataParameter<String> Name = EntityDataManager.<String>createKey(IvVillager.class, DataSerializers.STRING);
    protected static final DataParameter<Integer> Gender = EntityDataManager.<Integer>createKey(IvVillager.class, DataSerializers.VARINT);
    private int careerId;
    private int careerLevel;
    private boolean isLookingForHome;
    private boolean areAdditionalTasksSet;
    protected final InventoryBasic villagerInventory;
    Random r = new Random();
    /** A multi-dimensional array mapping the various professions, careers and career levels that a Villager may offer */
	protected String[] male_list = {"Bob", "Joseph", "Aaron", "Philp", "Adam", "Paul", "Donald", "Ryan", 
									"Mark", "Brian", "Robert", "Willam", "Harold", "Anthony", "Julius", 
									"Mathew", "Tyler", "Noah", "Patrick", "Caden", "Michael", "Jeffery",
									"James", "John", "Thomas", "Otto", "Bill", "Sheldon", "Leonard", 
									"Howard", "Carter", "Theodore", "Herbert"};
	protected String[] female_list = {"Karen", "Lessie", "Kayla", "Brianna", "Isabella", "Elizabeth",
									  "Kira", "Jadzia", "Abigail", "Chloe", "Olivia", "Sophia", "Emily", 
									  "Charlotte", "Amelia", "Maria", "Daria", "Sarah", "Theodora",
									  "Tia", "Jennifer", "Anglica", "Denna", "Tasha", "Catherine", "Lily",
									  "Amy", "Penny", "Julina", "Audrey", "Avery"};
	
	public IvVillager(World world) {
		super(world);
        this.villagerInventory = new InventoryBasic("Items", false, 20);
	}
	public IvVillager(World world, int professionId) {
		super(world, professionId);
	    this.setProfession(professionId);
        this.villagerInventory = new InventoryBasic("Items", false, 20);
	}
	public InventoryBasic getVillagerInventory()
    {
        return this.villagerInventory;
    }
	@Override
	protected void entityInit()
    {
		super.entityInit();
		this.getDataManager().register(Gender, Integer.valueOf(0));
		this.getDataManager().register(Name, String.valueOf("None"));
    }
	@Override
	protected void initEntityAI()
    {
        this.tasks.addTask(0, new EntityAISwimming(this));
        this.tasks.addTask(1, new EntityAIAvoidEntity(this, EntityZombie.class, 8.0F, 0.6D, 0.6D));
        this.tasks.addTask(1, new EntityAIAvoidEntity(this, EntityEvoker.class, 12.0F, 0.8D, 0.8D));
        this.tasks.addTask(1, new EntityAIAvoidEntity(this, EntityVindicator.class, 8.0F, 0.8D, 0.8D));
        this.tasks.addTask(1, new EntityAIAvoidEntity(this, EntityVex.class, 8.0F, 0.6D, 0.6D));
        this.tasks.addTask(1, new EntityAITradePlayer(this));
        this.tasks.addTask(2, new EntityAILookAtTradePlayer(this));
        this.tasks.addTask(2, new EntityAIMoveIndoors(this));
        this.tasks.addTask(3, new EntityAIRestrictOpenDoor(this));
        this.tasks.addTask(4, new EntityAITempt(this, 1.25D, Items.EMERALD, false));
        this.tasks.addTask(4, new EntityAIOpenDoor(this, true));
        this.tasks.addTask(5, new EntityAIMoveTowardsRestriction(this, 0.6D));
        this.tasks.addTask(6, new VilsPerDoor(this));
        this.tasks.addTask(7, new EntityAIFollowGolem(this));
        this.tasks.addTask(9, new EntityAIWatchClosest2(this, EntityPlayer.class, 3.0F, 1.0F));
        this.tasks.addTask(9, new EntityAIVillagerInteract(this));
        this.tasks.addTask(9, new EntityAIWanderAvoidWater(this, 0.6D));
        this.tasks.addTask(10, new EntityAIWatchClosest(this, EntityLiving.class, 8.0F));
    }
	public int getGender()
    {
        return ((Integer)this.getDataManager().get(Gender)).intValue();
    }
	public void setGender(int value)
	{
		this.getDataManager().set(Gender, Integer.valueOf(value));
	}
	public String getName()
	{
        return ((String)this.getDataManager().get(Name));
	}
	public void setName(String value)
	{
		this.getDataManager().set(Name, String.valueOf(value));
	}
	private void setAdditionalAItasks()
    {
        if (!this.areAdditionalTasksSet)
        {
            this.areAdditionalTasksSet = true;

            if (this.isChild())
            {
                this.tasks.addTask(8, new EntityAIPlay(this, 0.32D));
            }
            else if (this.getProfession() == 0)
            {
                this.tasks.addTask(6, new EntityAIHarvestFarmland(this, 0.6D));
            }
        }
    }
	 @Override
	 public void writeEntityToNBT(NBTTagCompound compound)
	    {
	        super.writeEntityToNBT(compound);
	        compound.setInteger("Profession", this.getProfession());
	        compound.setString("ProfessionName", this.getProfessionForge().getRegistryName().toString());
	        compound.setInteger("Riches", this.wealth);
	        compound.setInteger("Career", this.careerId);
	        compound.setInteger("CareerLevel", this.careerLevel);
	        compound.setBoolean("Willing", this.isWillingToMate);

	        if (this.buyingList != null)
	        {
	            compound.setTag("Offers", this.buyingList.getRecipiesAsTags());
	        }

	        NBTTagList nbttaglist = new NBTTagList();

	        for (int i = 0; i < this.getVillagerInventory().getSizeInventory(); ++i)
	        {
	            ItemStack itemstack = this.villagerInventory.getStackInSlot(i);

	            if (!itemstack.isEmpty())
	            {
	                nbttaglist.appendTag(itemstack.writeToNBT(new NBTTagCompound()));
	            }
	        }

	        compound.setTag("Inventory", nbttaglist);
	        if (world.isRemote == false){
	        	if (this.getGender() != 1 || this.getGender() != 2){
	        		this.gender = r.nextInt(2) + 1;
	        	}
	        	compound.setInteger("Gender", this.gender);
	        	if (this.getName() == null || this.getName() == "None"){
	        		if (this.gender == 1){
	        			this.name = male_list[r.nextInt(male_list.length)];
	        			System.out.println("Male Name");
	        		}
	        		else if (this.gender == 2){
	        			this.name = female_list[r.nextInt(male_list.length)];
	        			System.out.println("Female Name");
	        		}
	        		else if (this.gender != 1|| this.gender != 2){
	        			this.name = "None";
	        			System.out.println("Something went wrong with gender, please report.");
	        			System.out.println("No Name");
	        		}
	        	compound.setString("Name", this.name);
	        	this.setGender(this.gender);
	        	this.setName(this.name);
	        }
	        }
	        
	    }
	 @Override
	 public void readEntityFromNBT(NBTTagCompound compound){
		 super.writeEntityToNBT(compound);
		 if (world.isRemote == false){
			 this.gender = compound.getInteger("Gender");
			 this.name = compound.getString("Name");
			 this.getGender();
			 this.getName();
			 this.setCustomNameTag(this.getName());
		 }
		 this.setProfession(compound.getInteger("Profession"));
	        if (compound.hasKey("ProfessionName"))
	        {
	            net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession p =
	                net.minecraftforge.fml.common.registry.VillagerRegistry.instance().getRegistry().getValue(new net.minecraft.util.ResourceLocation(compound.getString("ProfessionName")));
	            if (p == null)
	                p = net.minecraftforge.fml.common.registry.VillagerRegistry.instance().getRegistry().getValue(new net.minecraft.util.ResourceLocation("minecraft:farmer"));
	            this.setProfession(p);
	        }
	        this.wealth = compound.getInteger("Riches");
	        this.careerId = compound.getInteger("Career");
	        this.careerLevel = compound.getInteger("CareerLevel");
	        this.isWillingToMate = compound.getBoolean("Willing");

	        if (compound.hasKey("Offers", 10))
	        {
	            NBTTagCompound nbttagcompound = compound.getCompoundTag("Offers");
	            this.buyingList = new MerchantRecipeList(nbttagcompound);
	        }

	        NBTTagList nbttaglist = compound.getTagList("Inventory", 10);

	        for (int i = 0; i < nbttaglist.tagCount(); ++i)
	        {
	            ItemStack itemstack = new ItemStack(nbttaglist.getCompoundTagAt(i));

	            if (!itemstack.isEmpty())
	            {
	                this.villagerInventory.addItem(itemstack);
	            }
	        }

	        this.setCanPickUpLoot(true);
	        this.setAdditionalAItasks();
		 
	 }
	 private void populateBuyingList()
	    {
	        if (this.careerId != 0 && this.careerLevel != 0)
	        {
	            ++this.careerLevel;
	        }
	        else
	        {
	            this.careerId = this.getProfessionForge().getRandomCareer(this.rand) + 1;
	            this.careerLevel = 1;
	        }

	        if (this.buyingList == null)
	        {
	            this.buyingList = new MerchantRecipeList();
	        }

	        int i = this.careerId - 1;
	        int j = this.careerLevel - 1;
	        java.util.List<EntityVillager.ITradeList> trades = this.getProfessionForge().getCareer(i).getTrades(j);

	        if (trades != null)
	        {
	            for (EntityVillager.ITradeList entityvillager$itradelist : trades)
	            {
	                entityvillager$itradelist.addMerchantRecipe(this, this.buyingList, this.rand);
	            }
	        }
	    }
	 @Override
	 public boolean processInteract(EntityPlayer player, EnumHand hand){
		if (world.isRemote == false){
			BlockPos blockpos = new BlockPos(this);
			this.villageObj = this.world.getVillageCollection().getNearestVillage(blockpos, 32);

		}
        ItemStack itemstack = player.getHeldItem(hand);
        if (itemstack.getItem() == IvItems.thieving_nose && !this.isChild()){
        	itemstack.damageItem(1, player);
        	this.setHealth(this.getHealth() - 2);
        	this.playHurtSound(getLastDamageSource());
        	if (rand.nextInt(10) + 1 < 6){
        		
        	}
        	if (rand.nextInt(10) + 1 < 9 && rand.nextInt(10) + 1  > 5){
        		this.entityDropItem(new ItemStack(Items.EMERALD, r.nextInt(2) + 1), 0);
        	}
        	if (rand.nextInt(10) + 1 < 10 && rand.nextInt(10) + 1  > 8){
        		this.entityDropItem(new ItemStack(Items.EMERALD, r.nextInt(2) + 1), 0);
        	}
        	if (world.isRemote == false){
        	if (this.villageObj != null)
	            {
	        		this.villageObj.modifyPlayerReputation(player.getName(), -2);
	            }
        	}
            return true;
        }
        else if (!this.holdingSpawnEggOfClass(itemstack, this.getClass()) && this.isEntityAlive() && !this.isTrading() && !this.isChild())
        {
            if (this.buyingList == null)
            {
                this.populateBuyingList();
            }

            if (hand == EnumHand.MAIN_HAND)
            {
                player.addStat(StatList.TALKED_TO_VILLAGER);
            }

            if (!this.world.isRemote && !this.buyingList.isEmpty())
            {
                this.setCustomer(player);
                player.displayVillagerTradeGui(this);
            }
            else if (this.buyingList.isEmpty())
            {
                return super.processInteract(player, hand);
            }

            return true;
        }
        else
        {
            return super.processInteract(player, hand);
        }
    }

}

 

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • So me and a couple of friends are playing with a shitpost mod pack and one of the mods in the pack is corail tombstone and for some reason there is a problem with it, where on death to fire the player will get kicked out of the server and the tombstone will not spawn basically deleting an entire inventory, it doesn't matter what type of fire it is, whether it's from vanilla fire/lava, or from modded fire like ice&fire/lycanites and it's common enough to where everyone on the server has experienced at least once or twice and it doesn't give any crash log. a solution to this would be much appreciated thank you!
    • It is 1.12.2 - I have no idea if there is a 1.12 pack
    • Okay, but does the modpack works with 1.12 or just with 1.12.2, because I need the Forge client specifically for Minecraft 1.12, not 1.12.2
    • Version 1.19 - Forge 41.0.63 I want to create a wolf entity that I can ride, so far it seems to be working, but the problem is that when I get on the wolf, I can’t control it. I then discovered that the issue is that the server doesn’t detect that I’m riding the wolf, so I’m struggling with synchronization. However, it seems to not be working properly. As I understand it, the server receives the packet but doesn’t register it correctly. I’m a bit new to Java, and I’ll try to provide all the relevant code and prints *The comments and prints are translated by chatgpt since they were originally in Spanish* Thank you very much in advance No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. MountableWolfEntity package com.vals.valscraft.entity; import com.vals.valscraft.network.MountSyncPacket; import com.vals.valscraft.network.NetworkHandler; import net.minecraft.client.Minecraft; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.animal.Wolf; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.Entity; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.network.PacketDistributor; public class MountableWolfEntity extends Wolf { private boolean hasSaddle; private static final EntityDataAccessor<Byte> DATA_ID_FLAGS = SynchedEntityData.defineId(MountableWolfEntity.class, EntityDataSerializers.BYTE); public MountableWolfEntity(EntityType<? extends Wolf> type, Level level) { super(type, level); this.hasSaddle = false; } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(DATA_ID_FLAGS, (byte)0); } public static AttributeSupplier.Builder createAttributes() { return Wolf.createAttributes() .add(Attributes.MAX_HEALTH, 20.0) .add(Attributes.MOVEMENT_SPEED, 0.3); } @Override public InteractionResult mobInteract(Player player, InteractionHand hand) { ItemStack itemstack = player.getItemInHand(hand); if (itemstack.getItem() == Items.SADDLE && !this.hasSaddle()) { if (!player.isCreative()) { itemstack.shrink(1); } this.setSaddle(true); return InteractionResult.SUCCESS; } else if (!level.isClientSide && this.hasSaddle()) { player.startRiding(this); MountSyncPacket packet = new MountSyncPacket(true); // 'true' means the player is mounted NetworkHandler.CHANNEL.sendToServer(packet); // Ensure the server handles the packet return InteractionResult.SUCCESS; } return InteractionResult.PASS; } @Override public void travel(Vec3 travelVector) { if (this.isVehicle() && this.getControllingPassenger() instanceof Player) { System.out.println("The wolf has a passenger."); System.out.println("The passenger is a player."); Player player = (Player) this.getControllingPassenger(); // Ensure the player is the controller this.setYRot(player.getYRot()); this.yRotO = this.getYRot(); this.setXRot(player.getXRot() * 0.5F); this.setRot(this.getYRot(), this.getXRot()); this.yBodyRot = this.getYRot(); this.yHeadRot = this.yBodyRot; float forward = player.zza; float strafe = player.xxa; if (forward <= 0.0F) { forward *= 0.25F; } this.flyingSpeed = this.getSpeed() * 0.1F; this.setSpeed((float) this.getAttributeValue(Attributes.MOVEMENT_SPEED) * 1.5F); this.setDeltaMovement(new Vec3(strafe, travelVector.y, forward).scale(this.getSpeed())); this.calculateEntityAnimation(this, false); } else { // The wolf does not have a passenger or the passenger is not a player System.out.println("No player is mounted, or the passenger is not a player."); super.travel(travelVector); } } public boolean hasSaddle() { return this.hasSaddle; } public void setSaddle(boolean hasSaddle) { this.hasSaddle = hasSaddle; } @Override protected void dropEquipment() { super.dropEquipment(); if (this.hasSaddle()) { this.spawnAtLocation(Items.SADDLE); this.setSaddle(false); } } @SubscribeEvent public static void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.START) { MinecraftServer server = net.minecraftforge.server.ServerLifecycleHooks.getCurrentServer(); if (server != null) { for (ServerPlayer player : server.getPlayerList().getPlayers()) { if (player.isPassenger() && player.getVehicle() instanceof MountableWolfEntity) { MountableWolfEntity wolf = (MountableWolfEntity) player.getVehicle(); System.out.println("Tick: " + player.getName().getString() + " is correctly mounted on " + wolf); } } } } } private boolean lastMountedState = false; @Override public void tick() { super.tick(); if (!this.level.isClientSide) { // Only on the server boolean isMounted = this.isVehicle() && this.getControllingPassenger() instanceof Player; // Only print if the state changed if (isMounted != lastMountedState) { if (isMounted) { Player player = (Player) this.getControllingPassenger(); // Verify the passenger is a player System.out.println("Server: Player " + player.getName().getString() + " is now mounted."); } else { System.out.println("Server: The wolf no longer has a passenger."); } lastMountedState = isMounted; } } } @Override public void addPassenger(Entity passenger) { super.addPassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(true)); } } } @Override public void removePassenger(Entity passenger) { super.removePassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is no longer mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(false)); } } } @Override public boolean isControlledByLocalInstance() { Entity entity = this.getControllingPassenger(); return entity instanceof Player; } @Override public void positionRider(Entity passenger) { if (this.hasPassenger(passenger)) { double xOffset = Math.cos(Math.toRadians(this.getYRot() + 90)) * 0.4; double zOffset = Math.sin(Math.toRadians(this.getYRot() + 90)) * 0.4; passenger.setPos(this.getX() + xOffset, this.getY() + this.getPassengersRidingOffset() + passenger.getMyRidingOffset(), this.getZ() + zOffset); } } } MountSyncPacket package com.vals.valscraft.network; import com.vals.valscraft.entity.MountableWolfEntity; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class MountSyncPacket { private final boolean isMounted; public MountSyncPacket(boolean isMounted) { this.isMounted = isMounted; } public void encode(FriendlyByteBuf buffer) { buffer.writeBoolean(isMounted); } public static MountSyncPacket decode(FriendlyByteBuf buffer) { return new MountSyncPacket(buffer.readBoolean()); } public void handle(NetworkEvent.Context context) { context.enqueueWork(() -> { ServerPlayer player = context.getSender(); // Get the player from the context if (player != null) { // Verifies if the player has dismounted if (!isMounted) { Entity vehicle = player.getVehicle(); if (vehicle instanceof MountableWolfEntity wolf) { // Logic to remove the player as a passenger wolf.removePassenger(player); System.out.println("Server: Player " + player.getName().getString() + " is no longer mounted."); } } } }); context.setPacketHandled(true); // Marks the packet as handled } } networkHandler package com.vals.valscraft.network; import com.vals.valscraft.valscraft; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.simple.SimpleChannel; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class NetworkHandler { private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel( new ResourceLocation(valscraft.MODID, "main"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals ); public static void init() { int packetId = 0; // Register the mount synchronization packet CHANNEL.registerMessage( packetId++, MountSyncPacket.class, MountSyncPacket::encode, MountSyncPacket::decode, (msg, context) -> msg.handle(context.get()) // Get the context with context.get() ); } }  
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.