Jump to content

Set/Get word on a GUI to/from NBT


joaopms

Recommended Posts

I have a GuiScreen and you can access it by right clicking a block. There, you can set the name of the player you want to detect when it is touching the block (I'm still working on it). If the block already was a name set, it will get it from the TileEntity NBT Data, and when you set the name on the GUI it will write it to the TileEntity NBT Data.

I've read that I will need to send and get packets to update the GUI and write to the TileEntity NBT Data, but I'm not sure if I need to do it using packets and how to do it.

Link to comment
Share on other sites

Make the GUI set a String variable in your tile entity to the text input.

If the text change send a packet containing the text to the server.

The server then reads the packet, and updates the TileEntity's String on the server side to the same value.

Then it should do something to mark the TE as updated so all players closeby it get's the update.

 

Inside the TileEntity class implement the read and write to/from nbt methods.

and save/load the string variable from NTB.

 

 

For more info on GUI and syncing check out the Interface Courses by vswe on http://courses.vswe.sw

 

NBT: There's some on the wiki.

Heres one for items but it should give you the general Idea of how you store and read a variable from NBT ;)

www.minecraftforge.net/wiki/Item_nbt

 

If you guys dont get it.. then well ya.. try harder...

Link to comment
Share on other sites

Make the GUI set a String variable in your tile entity to the text input.

If the text change send a packet containing the text to the server.

The server then reads the packet, and updates the TileEntity's String on the server side to the same value.

Then it should do something to mark the TE as updated so all players closeby it get's the update.

 

Inside the TileEntity class implement the read and write to/from nbt methods.

and save/load the string variable from NTB.

 

 

For more info on GUI and syncing check out the Interface Courses by vswe on http://courses.vswe.sw

 

NBT: There's some on the wiki.

Heres one for items but it should give you the general Idea of how you store and read a variable from NBT ;)

www.minecraftforge.net/wiki/Item_nbt

 

Man, Packets are confusing and complicated and took me almost 4 hours to figure that out, but I did it - I think - but when I set the name and close and then open the GUI it doesn't get the new name (unless I log out). Also, every Block was the same name and every block should have their own name.

Here's my code if you need it:

 

BlockIdentification.java

public class BlockIdentification extends BlockContainer {
public BlockIdentification(int id, Material material) {
	super(id, material);
	setHardness(2.0F);
	setStepSound(Block.soundStoneFootstep);
	setUnlocalizedName("identificationBlock");
	setCreativeTab(UsefulBlocks.tabUsefulBlocks);
}

public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float par7, float par8, float par9) {
	TileEntityIdentification t = (TileEntityIdentification) world.getBlockTileEntity(x, y, z);
	t.update(world);
	player.openGui(UsefulBlocks.instance, 0, world, x, y, z);
	return true;
}

@Override
public boolean hasTileEntity(int meta) {
	return true;
}

@Override
public TileEntity createNewTileEntity(World world) {
	return new TileEntityIdentification();
}
}

 

TileEntity.java

public class TileEntityIdentification extends TileEntity {
private static String name;

public TileEntityIdentification() {
}

@Override
public void writeToNBT(NBTTagCompound nbt) {
   super.writeToNBT(nbt);
   if (PacketHandler.getIdentificationName() != null) {
	   nbt.setString("name", PacketHandler.getIdentificationName());
   }
   System.out.println("NBT - Write");
}

@Override
public void readFromNBT(NBTTagCompound nbt) {
   super.readFromNBT(nbt);
   TileEntityIdentification.name = nbt.getString("name");
   System.out.println("NBT: " + TileEntityIdentification.name);
   PacketHandler.setIdentificationName(name);
}

public static String getName() {
	return name;
}

public void update(World world) {
	world.notifyBlockChange(xCoord, yCoord, zCoord, 2);
	worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
}

 

GuiIdentification.java

public class GuiIdentification extends GuiScreen {
public final int xSize = 176;
public final int ySize = 88;
private GuiTextField name;
private String nameString;

public GuiIdentification(TileEntityIdentification tileEntity) {
}

@SuppressWarnings("unchecked")
@Override
public void initGui() {
	Keyboard.enableRepeatEvents(true);
	int posX = (this.width - xSize) / 2;
	int posY = (this.height - ySize) / 2;
	this.buttonList.add(new GuiButton(0, posX + 7, posY + 60, 162, 20, "Set Player Name"));
	this.name = new GuiTextField(this.fontRenderer, posX + 8, posY + 35, 160, 20);
	this.name.setFocused(true);
	if (TileEntityIdentification.getName() != null) {
		this.name.setText(TileEntityIdentification.getName());
	}
}

@Override
public void drawScreen(int x, int y, float f) {
	this.drawDefaultBackground();

	GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
	this.mc.renderEngine.func_110577_a(new ResourceLocation("usefulblocks:textures/gui/IdentificationBlock.png"));

	int posX = (this.width - xSize) / 2;
	int posY = (this.height - ySize) / 2;

	this.drawTexturedModalRect(posX, posY, 0, 0, xSize, ySize);

	this.fontRenderer.drawString("Identification Block", posX + 40, posY + 15, 4210752);
	this.name.drawTextBox();

	super.drawScreen(x, y, f);
}

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

@Override
    public void onGuiClosed() {
        Keyboard.enableRepeatEvents(false);
    }

@Override
public void updateScreen() {
	name.updateCursorCounter();
    }

@Override
protected void mouseClicked(int par1, int par2, int par3) {
   super.mouseClicked(par1, par2, par3);
   name.mouseClicked(par1, par2, par3);
}

protected void actionPerformed(GuiButton par1GuiButton) {
	if (par1GuiButton.enabled) {
            if (par1GuiButton.id == 0) {
            	System.out.println("Name: " + nameString);
            	if (nameString != null) {
            		PacketHandler.setIdentificationName(nameString);
            	}
            }
	}
}

@Override
protected void keyTyped(char par1, int par2) {
   if (name.isFocused()) {
        name.textboxKeyTyped(par1, par2);
        nameString = name.getText();
   }

	if (par2 == 1) {
		this.mc.thePlayer.closeScreen();
	}
}
}
}

 

PacketHandler.java

public class PacketHandler implements IPacketHandler {
private static String identificationName;

@Override
public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player player) {
	ByteArrayDataInput reader = ByteStreams.newDataInput(packet.data);
	identificationName = reader.readUTF();
}

public static void setIdentificationName(String name) {
	ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
	DataOutputStream dataStream = new DataOutputStream(byteStream);

	try {
		dataStream.writeUTF(name);
	} catch (IOException e) {
		System.err.append("Failed to send identification name packet");
	}

	System.out.println("Packet: " + name);
	PacketDispatcher.sendPacketToServer(PacketDispatcher.getPacket(Reference.ModID, byteStream.toByteArray()));
}

public static String getIdentificationName() {
	System.out.println("Packet Read: " + identificationName);
	return identificationName;
}
}

Link to comment
Share on other sites

Make the GUI set a String variable in your tile entity to the text input.

If the text change send a packet containing the text to the server.

The server then reads the packet, and updates the TileEntity's String on the server side to the same value.

Then it should do something to mark the TE as updated so all players closeby it get's the update.

 

Inside the TileEntity class implement the read and write to/from nbt methods.

and save/load the string variable from NTB.

 

 

For more info on GUI and syncing check out the Interface Courses by vswe on http://courses.vswe.sw

 

NBT: There's some on the wiki.

Heres one for items but it should give you the general Idea of how you store and read a variable from NBT ;)

www.minecraftforge.net/wiki/Item_nbt

 

Man, Packets are confusing and complicated and took me almost 4 hours to figure that out, but I did it - I think - but when I set the name and close and then open the GUI it doesn't get the new name (unless I log out). Also, every Block was the same name and every block should have their own name.

Here's my code if you need it:

 

BlockIdentification.java

public class BlockIdentification extends BlockContainer {
public BlockIdentification(int id, Material material) {
	super(id, material);
	setHardness(2.0F);
	setStepSound(Block.soundStoneFootstep);
	setUnlocalizedName("identificationBlock");
	setCreativeTab(UsefulBlocks.tabUsefulBlocks);
}

public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float par7, float par8, float par9) {
	TileEntityIdentification t = (TileEntityIdentification) world.getBlockTileEntity(x, y, z);
	t.update(world);
	player.openGui(UsefulBlocks.instance, 0, world, x, y, z);
	return true;
}

@Override
public boolean hasTileEntity(int meta) {
	return true;
}

@Override
public TileEntity createNewTileEntity(World world) {
	return new TileEntityIdentification();
}
}

 

TileEntity.java

public class TileEntityIdentification extends TileEntity {
private static String name;

public TileEntityIdentification() {
}

@Override
public void writeToNBT(NBTTagCompound nbt) {
   super.writeToNBT(nbt);
   if (PacketHandler.getIdentificationName() != null) {
	   nbt.setString("name", PacketHandler.getIdentificationName());
   }
   System.out.println("NBT - Write");
}

@Override
public void readFromNBT(NBTTagCompound nbt) {
   super.readFromNBT(nbt);
   TileEntityIdentification.name = nbt.getString("name");
   System.out.println("NBT: " + TileEntityIdentification.name);
   PacketHandler.setIdentificationName(name);
}

public static String getName() {
	return name;
}

public void update(World world) {
	world.notifyBlockChange(xCoord, yCoord, zCoord, 2);
	worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
}

 

GuiIdentification.java

public class GuiIdentification extends GuiScreen {
public final int xSize = 176;
public final int ySize = 88;
private GuiTextField name;
private String nameString;

public GuiIdentification(TileEntityIdentification tileEntity) {
}

@SuppressWarnings("unchecked")
@Override
public void initGui() {
	Keyboard.enableRepeatEvents(true);
	int posX = (this.width - xSize) / 2;
	int posY = (this.height - ySize) / 2;
	this.buttonList.add(new GuiButton(0, posX + 7, posY + 60, 162, 20, "Set Player Name"));
	this.name = new GuiTextField(this.fontRenderer, posX + 8, posY + 35, 160, 20);
	this.name.setFocused(true);
	if (TileEntityIdentification.getName() != null) {
		this.name.setText(TileEntityIdentification.getName());
	}
}

@Override
public void drawScreen(int x, int y, float f) {
	this.drawDefaultBackground();

	GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
	this.mc.renderEngine.func_110577_a(new ResourceLocation("usefulblocks:textures/gui/IdentificationBlock.png"));

	int posX = (this.width - xSize) / 2;
	int posY = (this.height - ySize) / 2;

	this.drawTexturedModalRect(posX, posY, 0, 0, xSize, ySize);

	this.fontRenderer.drawString("Identification Block", posX + 40, posY + 15, 4210752);
	this.name.drawTextBox();

	super.drawScreen(x, y, f);
}

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

@Override
    public void onGuiClosed() {
        Keyboard.enableRepeatEvents(false);
    }

@Override
public void updateScreen() {
	name.updateCursorCounter();
    }

@Override
protected void mouseClicked(int par1, int par2, int par3) {
   super.mouseClicked(par1, par2, par3);
   name.mouseClicked(par1, par2, par3);
}

protected void actionPerformed(GuiButton par1GuiButton) {
	if (par1GuiButton.enabled) {
            if (par1GuiButton.id == 0) {
            	System.out.println("Name: " + nameString);
            	if (nameString != null) {
            		PacketHandler.setIdentificationName(nameString);
            	}
            }
	}
}

@Override
protected void keyTyped(char par1, int par2) {
   if (name.isFocused()) {
        name.textboxKeyTyped(par1, par2);
        nameString = name.getText();
   }

	if (par2 == 1) {
		this.mc.thePlayer.closeScreen();
	}
}
}
}

 

PacketHandler.java

public class PacketHandler implements IPacketHandler {
private static String identificationName;

@Override
public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player player) {
	ByteArrayDataInput reader = ByteStreams.newDataInput(packet.data);
	identificationName = reader.readUTF();
}

public static void setIdentificationName(String name) {
	ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
	DataOutputStream dataStream = new DataOutputStream(byteStream);

	try {
		dataStream.writeUTF(name);
	} catch (IOException e) {
		System.err.append("Failed to send identification name packet");
	}

	System.out.println("Packet: " + name);
	PacketDispatcher.sendPacketToServer(PacketDispatcher.getPacket(Reference.ModID, byteStream.toByteArray()));
}

public static String getIdentificationName() {
	System.out.println("Packet Read: " + identificationName);
	return identificationName;
}
}

 

All blocks the same name? Easy fix. Don't make the variable static. A static variable means that every instance of that class will have the same value for that variable.

 

The updating of the GUI? Fairly easy. You just need a string within the GUI that you use for sending the change. When the GUI get's opened, use a packet to tell the client what the server has as the string. So, something like:

public GuiRandom ( TileEntityRandom theRandomTileEntity ) {
    RandomPacketThing.sendToPlayer ( Minecraft.getMinecraft ().thePlayer );
    theStringThatHoldsThePlayerName =theRandomTileEntity.getTheString ();
}

I am Mew. The Legendary Psychic. I behave oddly and am always playing practical jokes.

 

I have also found that I really love making extremely long and extremely but sometimes not so descriptive variables. Sort of like what I just did there xD

Link to comment
Share on other sites

The updating of the GUI? Fairly easy. You just need a string within the GUI that you use for sending the change. When the GUI get's opened, use a packet to tell the client what the server has as the string.

All blocks the same name? Easy fix. Don't make the variable static. A static variable means that every instance of that class will have the same value for that variable.

Okay, I've done the packet thing, but it stays the same because the string is static and if I try to change it, it throws me a couple of errors, like "Cannot make a static reference to the non-static method getIdentificationName() from the type PacketHandler" and it only allows me to change it back to static.

Nevermind, I was forgetting how to do it properly.

Link to comment
Share on other sites

I have another problem: my variables aren't working as they should (check the code):

public class TileEntityIdentification extends TileEntity {
public String setName;
public String getName;

public TileEntityIdentification() {

}

public void setName(String s) {
	setName = s; //called from the packethandler via the gui
	System.out.println("setName: " + setName); // this works
}


public String getName() {
	//System.out.println("getName: " + getName);
	return getName; // returns null - should return the name on the block (get)
}

public void readFromNBT(NBTTagCompound nbt) {
   super.readFromNBT(nbt);
   getName = nbt.getString("name"); // returns null - should return the name on the block (get)
   PacketHandler.setIdentificationName(getName); // returns null - should return the name on the block (get) || to be used on the gui
   //System.out.println("Read NBT: " + getName);
}

public void writeToNBT(NBTTagCompound nbt) {
   super.writeToNBT(nbt);
   //System.out.println("NBT Write: " + setName);
   nbt.setString("name", setName); // is null - should be the name on the block (set) || set from the gui via packet
}
}

Link to comment
Share on other sites

joaopms, you should check out http://courses.vswe.se

it will learn you all the basics of the arts to which you are an apprentice ;)

 

Also it will introduce you to packets, Guis, models, server->client "instant" sync, and much much more.

It's way better than any tutorial on the wiki or anywhere else and it's the most complete introduction to minecraft modding you can find.

 

It's not a tutorial, it's an actual course you take, and it's 100% free!

I advise you to take your time to follow those courses, from start to end without skipping lectures or assignments.

 

Start with "a cup of java" and move down the lists of lectures and then do the next course after completing the assignment.

Do those courses and pass the final assignment and tho shall be a mere apprentice no more ;)

If you guys dont get it.. then well ya.. try harder...

Link to comment
Share on other sites

You are using two different variables.  ???

They don't know about each other unless read/write NBT happens, which doesn't that often.

The one "name" variable was good.

Hmm... didn't know about that.

But I've changed it and it persists:

public class TileEntityIdentification extends TileEntity {
public String name;

public TileEntityIdentification() {

}

public void setName(String s) {
	name = s; //called from the packethandler via the gui
	System.out.println("setName: " + name); // this works
}

public void readFromNBT(NBTTagCompound nbt) {
   super.readFromNBT(nbt);
   name = nbt.getString("name"); // returns null - should return the name on the block (get)
   PacketHandler.setIdentificationName(name); // returns null - should return the name on the block (get) || to be used on the gui
   System.out.println("Read NBT: " + name); // this doesn't work because it doesn't have any data, yet
}

public void writeToNBT(NBTTagCompound nbt) {
   super.writeToNBT(nbt);
   System.out.println("NBT Write: " + name); // this fails
   nbt.setString("name", name); // is null - should be the name on the block (set) || set from the gui via packet
}

public String getName() {
	System.out.println("getName: " + name);  // this fails
	return name; // returns null - should return the name on the block (get)
}
}

Link to comment
Share on other sites

joaopms, you should check out http://courses.vswe.se

it will learn you all the basics of the arts to which you are an apprentice ;)

 

Also it will introduce you to packets, Guis, models, server->client "instant" sync, and much much more.

It's way better than any tutorial on the wiki or anywhere else and it's the most complete introduction to minecraft modding you can find.

 

It's not a tutorial, it's an actual course you take, and it's 100% free!

I advise you to take your time to follow those courses, from start to end without skipping lectures or assignments.

 

Start with "a cup of java" and move down the lists of lectures and then do the next course after completing the assignment.

Do those courses and pass the final assignment and tho shall be a mere apprentice no more ;)

Yeah, I will need to do that. Checking it when I need it isn't enought.

Thanks!

Link to comment
Share on other sites

I don't know if you still have this in your Packet handler, but just in case:

private static String identificationName;

@Override
public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player player) {
	ByteArrayDataInput reader = ByteStreams.newDataInput(packet.data);
	identificationName = reader.readUTF();
}

Don't store a (static  ::)) value, actually do something to the tile entity.

Link to comment
Share on other sites

I don't know if you still have this in your Packet handler, but just in case:

private static String identificationName;

@Override
public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player player) {
	ByteArrayDataInput reader = ByteStreams.newDataInput(packet.data);
	identificationName = reader.readUTF();
}

Don't store a (static  ::)) value, actually do something to the tile entity.

Yes, I've changed the static value.

Do something to the tile entity? I think I already have that: the identificationName string is used to read the packet and then send save it to NBT.

Link to comment
Share on other sites

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



×
×
  • Create New...

Important Information

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