Jump to content

[SOLVED] getLocalizedName() - How do I call this properly?


Recommended Posts

Posted

        	public static String blockName() {
	return CollumStone.getLocalizedName();
        }

 

Hey I'm having a little trouble with this... I'm trying to call my blocks name - however the getLocalizedName is not static and it has to be so i can call it from other classes using...

 

               public ResourceLocation texture = new ResourceLocation(KimptonCore.modid + ":" + CollumStone.blockName());

 

The first piece of code is from my block's template file and the second piece of code (a different .java file) is ordering textures. I have many blocks all wanting to use the same model so it seemed pointless to make a different template for every block I want to make.

 

 

I submitted this about a month ago: I was told to go learn ''basic java'' and that's what I did - however in the last months worth of research reading etc I still haven't solved this any more. Although it has allowed me to neaten up some code. I understand that non static methods can't call static ones - I just need a way around this xD thanks.

Posted

You do know there is a way to call, say,

CollumStone.getUnlocalizedName().substring(5);

to get the name?

 

Because that is what you are supposed to use. And then you can model your texture names after that.

 

I guess if you really wanted to, you could do this:

private static String blockName = CollumStone.getLocalizedName();

public static String blockName()
{
        return blockName;
}

 

And as I hinted at earlier, your texture names should not be capitalised and have spaces...

We all stuff up sometimes... But I seem to be at the bottom of that pot.

Posted

private static String blockName = CollumStone.getLocalizedName();

 

Ah you see you would have the same problem as me: getLocalizedName is NOT static and therefore any stings you make that include it are also not allowed to be static :( I've tried this. Thanks anyway :)

Posted

CollumStone.getUnlocalizedName().substring(5);

 

That is also not allowed to be static - maybe I should change my calling method for the texture ATM it is:

 

public ResourceLocation texture = new ResourceLocation(KimptonCore.modid + ":" + CollumStone.blockName());

 

ResourceLocation is static and I cannot change that.

Posted

Umm... Did you actually TRY what I said? The private static String blockName?

 

Because I am sorry to tell you, but I know Java. And I also tested it. You can't call a non static method from a static method. You can make a static variable equal a non static variable though. Please, learn Java if you haven't already! And if you have, please do some more learning!

 

You have had a great misconception, I am sorry to say.

We all stuff up sometimes... But I seem to be at the bottom of that pot.

Posted

private static String blockName = CollumStone.getLocalizedName();

 

Ah you see you would have the same problem as me: getLocalizedName is NOT static and therefore any stings you make that include it are also not allowed to be static :( I've tried this. Thanks anyway :)

 

Um, actually getLocalizedName() is a public method for all blocks.  Here is the implementation from the Block class:

    /**
     * Gets the localized name of this block. Used for the statistics page.
     */
    public String getLocalizedName()
    {
        return StatCollector.translateToLocal(this.getUnlocalizedName() + ".name");
    }

 

I have no idea why you are putting that into a private variable, but you can call the method above at any time from anywhere.

 

[EDIT]Also you need to understand that there is difference between localized and unlocalized name, but you can sort of convert between them if necessary.  @Kwibble was mentioning how you can strip the "tile." part off with his substring example above.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Posted

Also: With the way that resource location is now - that is pointing to /assets/[YOUR MOD ID]/collumstone (if the CollumStone's name is collum stone).

We all stuff up sometimes... But I seem to be at the bottom of that pot.

Posted

@jabelar If you read what I said you would understand. Kimpton here seems insistent on having a static method blockName(). And so I was giving him the means to actually do that...

We all stuff up sometimes... But I seem to be at the bottom of that pot.

Posted

http://gyazo.com/16cc40857366d7b0734116756c4cd8d8

 

..? Ok CollumStone has been renamed to BlockProperties (sorry for the confusion - I'm not alone working on this)

 

I think you are doing it backwards.  You should set the static block name variable directly with string containing the name you want, and then you should use that to assign the unlocalized name, and then use lang file to do the conversion to localized name. 

 

A "static" essentially means you want it to be a constant, but the localized name can theoretically change during the game so it doesn't make sense to do it this way.  I think you should question why you need a static variable when you can call the public method at any time you need it?

 

Anyway, I think what you want to do is put the name string directly into that field initialization and then set the unlocalized name based on that.  Then everything will match.

 

In other words, the localized name should come from this variable; you should not be assigning this variable from method that looks up localized name.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Posted

ClassWhereYouDeclareYourBlockIn.YOUR_BLOCK.getLocalizedName();

 

Now I know that works.. I have to rush about 100 blocks using the same model, render class and they all having the same properties - It would have been nice if I just took the name without me having to make a new class for every rendered block... That was my ultimate aim

Posted

I knew that also xD I'm having difficulty executing this.. basically this piece of code...

public ResourceLocation texture = new ResourceLocation(KimptonCore.modid + ":" + KimptonCore.CollumStone.getLocalizedName());

 

where it says KimptonCore.CollumStone.getLocalizedName()) needs to say something along the lines of ''getUnlocalizedName" so that depending on what block is calling this class it grabs the appropriate texture depending on the name of the instance that's calling it. How do I do this...?

Posted

Okay, here's the deal.  Blocks are (I suppose) a little bit confusing in Minecraft because there is one class, one instance, but lots of blocks!  How does that work?  Well, there is some sort of map of the locations of all the places the block should render, and there is record of "metadata" per block that allows some differentiation (like a door can face different directions).  But it actually still only one block instance from Java perspective!

 

I suppose this can make the Java confusing.  Basically something like the texture and unlocalized name are not static but are the same for all the blocks because there is really only one instance of the block in the game.  But because it is an instance it doesn't need to be a static class variable, and in fact as you're experiencing it could create some issues with trying to treat it that way.

 

So you should not be using class variables and methods, but rather you should be using instance methods.  They are still unique to the single block instance.

 

If for some reason you want different names or textures for some of your blocks, you need to either use metadata or create an associated TileEntity to contain the unique stuff.

 

So somewhere in your code you should be creating the instance of your block, and you should call your methods and access your fields in that instance.  Instead of KimptonCore.CollumStone. (the class) you should be using the instance name you stored somewhere in your main class or proxy.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Posted

Ok so here is where I am at:

This is from KimptonCore (my main class)

    	//Define Block Properties
    	CollumStone = new BlockProperties(Material.rock).setBlockName("ModelCollumStone");
    	
    	//Registering Blocks
    	GameRegistry.registerBlock(CollumStone, "ModelCollumStone"); 
    	
    	//Registering Tile Entities
    	GameRegistry.registerTileEntity(TileEntityBlock.class, "ModelCollumStone"); 

 

by setting my Block Name I have set an ''Unlocalized Name'' correct?

 

Here is my code from the texture of the particles breaking when the block is destroyed

This is from my BlockProperties class.

@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister iconRegister){
	this.blockIcon = iconRegister.registerIcon(KimptonCore.modid + ":" + this.getUnlocalizedName().substring(5));
}

 

Where is says getUnlocalizedName is where its grabbing the calling block's texture by using its name I have set. Why can't I apply the same logic to this:

This is from my tile entity render class.

public ResourceLocation texture = new ResourceLocation(KimptonCore.modid + ":" + KimptonCore.CollumStone.getUnlocalizedName());

 

I understand why I cant use ''this.'' as its calling something from a different class... but having ''.CollumStone." means that for every time I wish to call the tile entity I would have to make a different ResourceLocation depending on what's calling it.

 

Jabelar everything you have said I understand except from this: "Instead of KimptonCore.CollumStone. (the class) you should be using the instance name you stored somewhere in your main class or proxy." How do I do that?

Posted

Jabelar everything you have said I understand except from this: "Instead of KimptonCore.CollumStone. (the class) you should be using the instance name you stored somewhere in your main class or proxy." How do I do that?

 

Okay, part of the problem in helping you is that you're not using proper naming convention.  You should have lower case "C" in "collumStone" otherwise it looks like you're calling a class not a field.

 

But based on the code you just posted, it seems like KimptonCor.CollumStone would be the instance and should work.  But you should rename this for proper convention as it can cause a lot of confusion when working with other coders.

 

I just checked some of my own code, and it seems to work fine -- no complaints about static and such.  I have, in my main class:

    public final static Block blockMagicBeanStalk = new BlockMagicBeanStalk();

 

Then in my tile entity for the block I have:

        String name = MagicBeans.blockMagicBeanStalk.getUnlocalizedName();

 

And it has no problem that I could see.  Note that I was calling the latter code in a public non-static method of the tile entity.  Is the method in your tile entity render class static?

 

 

 

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Posted

Okay that's understood - sometimes I mix the terms people who code in java use - it was alot simpler when learning the arduino code ahah :) Anyway - as i said in my last post - is there a way i can skip it looking for a specific block (in this case .collumStone) and rather just call getUnlocalizedName and use the calling blocks name?

Posted

Here I declare basic block properties and this is what I call the ''Calling Block''

This is in Kimpton Core

collumStone = new BlockProperties(Material.rock).setBlockName("ModelCollumStone");

 

it says ''new BlockProperies''

 

In BlockProperties I'm able to use these lines to set the particles texture:

@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister iconRegister){
	this.blockIcon = iconRegister.registerIcon(KimptonCore.modid + ":" + this.getUnlocalizedName().substring(5));
}

 

NOTE: I didn't make a reference the the specific texture but used the calling blocks name to grab the texture. Basically I want todo this in this:

public ResourceLocation texture = new ResourceLocation(KimptonCore.modid + ":" + KimptonCore.collumStone.getLocalizedName());

 

Which is in Tile entity Renderer - where it says ''KimptonCore.collumStone.getLocalizedName'' I need it to say "getUnlocalizedName().substring(5)" (not that that obviously, as that doesn't work). Therefore I need a way around this so I don't have to keep making more tile entity render classes for each block. I don't want a mod with over 100 classes with slight alterations - that's stupid.

Posted

Hey diesieben - that worked :) Although you came across there a little rude, I thank you for telling me how todo it :) I can move forward with my code :D That was a learning curve for me, although I have spent the last month solidly working on fundamentals of java, its all still rather raw in my mind and I'm still struggling with basic concepts *sigh*. Sorry about the bumping there, won't happen again.

 

Hey jabelar - idk why but I've taken a like to you aha :) You're very knowledgeable (just like most of you) and I thank you in taking an interest.

 

General: I've solved it - exactly how diesieben said how to set it out :) Issue: SOLVED!

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

    • 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.