Jump to content

Recommended Posts

Posted

Hello, I need tot be able to spawn an entity with existing nbt data. When I try to do this it crashes and says that it is a null pointer exception.

 

More info:

Basically I have a tile entity that scans for a random entity around it, and it saves that entity in its self. It then kills the entity and on game exit it saves the entity nbt by using these lines of code: 

     

NBTTagCompound compound2 = new NBTTagCompound();

      compound2.setString("id", EntityList.getEntityString(this.capturedEntity));

      this.capturedEntity.writeToNBT(compound2);

       

      compound.setTag("EntityData", compound2);

 

 

Then when I load it  I use these lines of code:

 

NBTTagCompound compound2 = (NBTTagCompound) compound.getTag("EntityData");

       

        if(compound2 != null) {

        this.targetEntity = (EntityLiving) EntityList.createEntityFromNBT(compound2, this.worldObj);

        this.capturedEntity = this.targetEntity;

        }

 

 

I tried printing the compound2 var and the entity obj out and they seem to display normal data, but when I try to spawn the entity in the world it crashes ans says that is is a Null Pointer Exception.

 

Full Code:

 

package mod.xtronius.htsm.tileEntity;

import java.util.ArrayList;
import java.util.List;

import mod.xtronius.htsm.entity.ai.EntityAIGoToCage;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.ai.EntityAITempt;
import net.minecraft.entity.passive.EntityPig;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;

public class TileEntityCage extends TileEntity implements IInventory{

private ItemStack[] cageContents = new ItemStack[3];

private boolean isCageClosed = false;

private EntityLiving targetEntity;
private EntityLiving capturedEntity;

private ArrayList<Entity> removedEntities = new ArrayList<Entity>();

private int timer = 0;

@Override
public void updateEntity() {

	if(!this.worldObj.isRemote) {

		float seconds = 1.5f;
		int delay = (int) (seconds * 20);

		if(timer <= delay) timer++;
		else timer = 0;

//			this.targetEntity = null;
//			this.capturedEntity = null;
//			this.isCageClosed = false;

		//TODO Remove test code
//			System.out.println("Target: " + targetEntity);
//			System.out.println("Capture: " + capturedEntity);
//			System.out.println("IsClosed: " + isCageClosed);

		if(timer == delay) {

			//Checks to see if the inv slots are filled
			if(this.getStackInSlot(0) != null && this.getStackInSlot(1) != null && this.getStackInSlot(2) != null && !this.isCageClosed) { //TODO Create an item stack array for checking specific items

				//Gets the block at the tile entities' postion
				Block block = this.worldObj.getBlock(this.xCoord, this.yCoord, this.zCoord);

				//Gets the bounding box of the block obtained above, then it offsets it and expands it
				AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(block.getBlockBoundsMinX(), block.getBlockBoundsMinY(), block.getBlockBoundsMinZ(), block.getBlockBoundsMaxX(), block.getBlockBoundsMaxY(), block.getBlockBoundsMaxZ());
				AxisAlignedBB aabb1 = aabb.getOffsetBoundingBox(this.xCoord, this.yCoord, this.zCoord);
				AxisAlignedBB aabb2 = aabb1.expand(10, 10, 10);

				//Gets all entities within this bounding box
				List<EntityPig> list = this.worldObj.getEntitiesWithinAABB(EntityPig.class, aabb2);

				for(EntityPig entity : list) {

					// Breaks if the cage is closed, if the entity is already in another list or if there is already a targeted entity;
					if(isCageClosed || this.targetEntity != null || this.capturedEntity != null) break;

					if(!this.removedEntities.contains(entity)) {
						//Math for calculating the percentage chance
						double rand = Math.random();
						double randPercent = rand < 0.75 ? rand : 0.75;
						double item = 1.0;
						double subPercent = (item * randPercent) < 1.0 ? (item * randPercent) : 1.0;
						double finalPercent = 1 - subPercent;

						double rand2 = Math.random();
						//TODO Remove test code
						//Test Code
//						double rand2 = 1;

						if(rand2 > finalPercent) {

							//Try to send the entity to the tile entities location, closes the gate and set the entity as the target entity
							System.out.println("Working");
							entity.getNavigator().tryMoveToXYZ(this.xCoord, yCoord, zCoord, 1.0f);
							this.isCageClosed = true;
							this.targetEntity = entity;
							break;
						} else {
							this.removedEntities.add(entity);
							System.out.println("Fail");
						}
					}
				}
			} else if(this.isCageClosed) {

				int range = 3;

				if(this.targetEntity != null) {
					if(this.targetEntity.posX > this.xCoord - range && this.targetEntity.posX < this.xCoord + range) {
						if(this.targetEntity.posY > this.yCoord - range && this.targetEntity.posY < this.yCoord + range) {
							if(this.targetEntity.posZ > this.zCoord - range && this.targetEntity.posZ < this.zCoord + range) {
								this.capturedEntity = this.targetEntity;
							} else
								if(this.targetEntity != null) ((EntityPig) this.targetEntity).getNavigator().tryMoveToXYZ(this.xCoord, yCoord, zCoord, 1.0f);
						} else
							if(this.targetEntity != null) ((EntityPig) this.targetEntity).getNavigator().tryMoveToXYZ(this.xCoord, yCoord, zCoord, 1.0f);
					} else
						if(this.targetEntity != null) ((EntityPig) this.targetEntity).getNavigator().tryMoveToXYZ(this.xCoord, yCoord, zCoord, 1.0f);
				}

//					//Checks if the targeted entity is not alive, if so then reset the main variables
//					if(this.capturedEntity != null) 
//						if(this.capturedEntity.isDead) resetVars();
//					
//					//Checks if the captured entity is not alive, if so then reset the main variables
//					if(this.capturedEntity != null) 
//						if(this.capturedEntity.isDead) resetVars();
			}
		}
	}
}

private void resetVars() { this.isCageClosed = false; this.targetEntity = null; this.capturedEntity = null; }

@Override
public void readFromNBT(NBTTagCompound compound) {
        super.readFromNBT(compound);   
        
        NBTTagList list = compound.getTagList("Items", 10);
        this.cageContents = new ItemStack[this.getSizeInventory()];

        for (int i = 0; i < list.tagCount(); ++i) {
            NBTTagCompound compound1 = list.getCompoundTagAt(i);
            int j = compound1.getByte("Slot") & 255;

            if (j >= 0 && j < this.cageContents.length) {
                this.cageContents[j] = ItemStack.loadItemStackFromNBT(compound1);
            }
        }
        
        NBTTagCompound compound2 = (NBTTagCompound) compound.getTag("EntityData");
        
        if(compound2 != null) {
        this.targetEntity = (EntityLiving) EntityList.createEntityFromNBT(compound2, this.worldObj);
        	this.capturedEntity = this.targetEntity;
        }
        
        if(this.capturedEntity != null) {
        	this.isCageClosed = true;
        }
    }

@Override
    public void writeToNBT(NBTTagCompound compound) {
        super.writeToNBT(compound);
        NBTTagList list = new NBTTagList();
        
        for (int i = 0; i < this.cageContents.length; ++i) {
            if (this.cageContents[i] != null) {
                NBTTagCompound compound1 = new NBTTagCompound();
                compound1.setByte("Slot", (byte)i);
                this.cageContents[i].writeToNBT(compound1);
                list.appendTag(compound1);
            }
        }
        
        compound.setTag("Items", list);
        
        if(this.capturedEntity != null) {
        NBTTagCompound compound2 = new NBTTagCompound();
        compound2.setString("id", EntityList.getEntityString(this.capturedEntity));
        this.capturedEntity.writeToNBT(compound2);
        
        compound.setTag("EntityData", compound2);
        }
    }

@Override
public int getSizeInventory() { return 3; }

@Override
public ItemStack getStackInSlot(int slot) { return this.cageContents[slot]; }

@Override
public ItemStack decrStackSize(int p_70298_1_, int p_70298_2_) {
	 if (this.cageContents[p_70298_1_] != null)
        {
            ItemStack itemstack;

            if (this.cageContents[p_70298_1_].stackSize <= p_70298_2_)
            {
                itemstack = this.cageContents[p_70298_1_];
                this.cageContents[p_70298_1_] = null;
                this.markDirty();
                return itemstack;
            }
            else
            {
                itemstack = this.cageContents[p_70298_1_].splitStack(p_70298_2_);

                if (this.cageContents[p_70298_1_].stackSize == 0)
                {
                    this.cageContents[p_70298_1_] = null;
                }

                this.markDirty();
                return itemstack;
            }
        }
        else
        {
            return null;
        }
}

@Override
public ItemStack getStackInSlotOnClosing(int slot) { return this.cageContents[slot]; }

@Override
public void setInventorySlotContents(int slot, ItemStack stack) { this.cageContents[slot] = stack; }

@Override
public String getInventoryName() { return "Cage"; }

@Override
public boolean hasCustomInventoryName() { return false; }

@Override
public int getInventoryStackLimit() { return 64; }

@Override
public boolean isUseableByPlayer(EntityPlayer player) { return this.worldObj.getTileEntity(this.xCoord, this.yCoord, this.zCoord) != this ? false : player.getDistanceSq((double)this.xCoord + 0.5D, (double)this.yCoord + 0.5D, (double)this.zCoord + 0.5D) <= 64.0D; }

@Override
public void openInventory() {}

@Override
public void closeInventory() {}

@Override
public boolean isItemValidForSlot(int slot, ItemStack stack) { return true; }
}

 

Don't be afraid to ask question when modding, there are no stupid question! Unless you don't know java then all your questions are stupid!

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

    • that happens every time I enter a new dimension.
    • This is the last line before the crash: [ebwizardry]: Synchronising spell emitters for PixelTraveler But I have no idea what this means
    • What in particular? I barely used that mod this time around, and it's never been a problem in the past.
    • Im trying to build my mod using shade since i use the luaj library however i keep getting this error Reason: Task ':reobfJar' uses this output of task ':shadowJar' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. So i try adding reobfJar.dependsOn shadowJar  Could not get unknown property 'reobfJar' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler. my gradle file plugins { id 'eclipse' id 'idea' id 'maven-publish' id 'net.minecraftforge.gradle' version '[6.0,6.2)' id 'com.github.johnrengelman.shadow' version '7.1.2' id 'org.spongepowered.mixin' version '0.7.+' } apply plugin: 'net.minecraftforge.gradle' apply plugin: 'org.spongepowered.mixin' apply plugin: 'com.github.johnrengelman.shadow' version = mod_version group = mod_group_id base { archivesName = mod_id } // Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17. java.toolchain.languageVersion = JavaLanguageVersion.of(17) //jarJar.enable() println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" minecraft { mappings channel: mapping_channel, version: mapping_version copyIdeResources = true runs { configureEach { workingDirectory project.file('run') property 'forge.logging.markers', 'REGISTRIES' property 'forge.logging.console.level', 'debug' arg "-mixin.config=derp.mixin.json" mods { "${mod_id}" { source sourceSets.main } } } client { // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. property 'forge.enabledGameTestNamespaces', mod_id } server { property 'forge.enabledGameTestNamespaces', mod_id args '--nogui' } gameTestServer { property 'forge.enabledGameTestNamespaces', mod_id } data { workingDirectory project.file('run-data') args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') } } } sourceSets.main.resources { srcDir 'src/generated/resources' } repositories { flatDir { dirs './libs' } maven { url = "https://jitpack.io" } } configurations { shade implementation.extendsFrom shade } dependencies { minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" implementation 'org.luaj:luaj-jse-3.0.2' implementation fg.deobf("com.github.Virtuoel:Pehkui:${pehkui_version}") annotationProcessor 'org.spongepowered:mixin:0.8.5:processor' minecraftLibrary 'luaj:luaj-jse:3.0.2' shade 'luaj:luaj-jse:3.0.2' } // Example for how to get properties into the manifest for reading at runtime. tasks.named('jar', Jar).configure { manifest { attributes([ 'Specification-Title' : mod_id, 'Specification-Vendor' : mod_authors, 'Specification-Version' : '1', // We are version 1 of ourselves 'Implementation-Title' : project.name, 'Implementation-Version' : project.jar.archiveVersion, 'Implementation-Vendor' : mod_authors, 'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"), "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", "TweakOrder" : 0, "MixinConfigs" : "derp.mixin.json" ]) } rename 'mixin.refmap.json', 'derp.mixin-refmap.json' } shadowJar { archiveClassifier = '' configurations = [project.configurations.shade] finalizedBy 'reobfShadowJar' } assemble.dependsOn shadowJar reobf { re shadowJar {} } publishing { publications { mavenJava(MavenPublication) { artifact jar } } repositories { maven { url "file://${project.projectDir}/mcmodsrepo" } } } my entire project:https://github.com/kevin051606/DERP-Mod/tree/Derp-1.0-1.20
  • Topics

×
×
  • Create New...

Important Information

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