javaminecraftminecraft-fabric

MinecraftClient.getInstance().player returns null


I have just started with trying to make a simple minecraft mod that returns the PlayerEntity DisplayName property and logs it to the console. The Code goes as follows:

SimpleMod.java

package net.arecdev.simplemod;

import net.fabricmc.api.ModInitializer;

import net.arecdev.simplemod.test.TestClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



public class SimpleMod implements ModInitializer {
    public static final String MOD_ID = "simplemod";
    public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);


    @Override
    public void onInitialize() {
        LOGGER.info("Simple Mod has started");


        String teststring = TestClass.test();
        LOGGER.info("String: " + teststring);
    }
}

TestClass.java

package net.arecdev.simplemod.test;


import net.minecraft.client.MinecraftClient;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.text.Text;



public class TestClass {

    public static String test() {


        PlayerEntity player = MinecraftClient.getInstance().player;
        Text playerDisplayName = player.getDisplayName();
        String playerDisplayString = playerDisplayName.getString();
        return playerDisplayString;
    }

}

when trying to run this with a Minecraft Client I get a NullPointerException:

Caused by: java.lang.NullPointerException: Cannot invoke "net.minecraft.entity.player.PlayerEntity.getDisplayName()" because "player" is null

I assume this happens because the MinecraftClient hasn't started at that point yet. So how do I wait till MinecraftClient has been initialized.


Solution

  • Have you checked the player is in a world? To get the Player entity the world needs to be loaded I believe. If the world or level is null the PlayerEntity should be null since there is no PlayerEntity that exists since there is no world.

    if (MinecraftClient.getInstance().level != null) {
        PlayerEntity player = MinecraftClient.getInstance().player;
        Text playerDisplayName = player.getDisplayName();
        String playerDisplayString = playerDisplayName.getString();
        return playerDisplayString;
    } else {
        // return "The player has not loaded in a world!" | return "1"
    }
    

    If you intent to get the username when the client first starts you should try to get the current account information received from the servers. I hope this helps!