Jump to content

GetServer() is Null / What is the best way to get a permanent server instance?


Recommended Posts

Apologies if this is a common topic. I've searched through topics on this forum and on Google, and the code I've found is mostly deprecated. I'm currently trying to get the server instance using the below code:



//Make given AI attack a random player on the server
    public AITargetPlayer(Entity Attacker)
        //Current Minecraft server
        MinecraftServer Curr_Server = Attacker.getServer();
        if(Curr_Server != null)
            LOGGER.info("SERVER IS ACTIVE");
            //Get curent game type. If is in survival, then, target player
            GameType Curr_GameType = Curr_Server.getDefaultGameType();
            if(Curr_GameType == GameType.SURVIVAL)
                LOGGER.info("GAME TYPE IS SURVIVAL");
                //Get list of current players in the game
                PlayerList Player_List = Attacker.getServer().getPlayerList();
                //Get random player index to have this mob attack
                int PlayerCount = Player_List.getPlayerCount();
                //If players in game, then
                if(PlayerCount > 0)
                    java.util.List<ServerPlayer> All_Players = Player_List.getPlayers();                
                    LOGGER.info("Targeting Player " + PlayerCount);
                    RNG R = new RNG(0,  PlayerCount);
                    int Selected_Index = (int)R.Value;
                    //Grab playwer in the list
                    ServerPlayer Targeted_Player = All_Players.get(Selected_Index);
                    //Cast to generic monster type
                    Monster Monster_Class = (Monster)Attacker; 
                    //Set attack target
                    //Set move block
                    Monster_Class.getNavigation().moveTo(Targeted_Player, Monster_Class.getSpeed());


I'm guessing this is the incorrect way to grab the server instance, as it's mostly null? What would be a better way, instead? Any documentation that might help on this? This class is invoked from a LivingEvent event, and "Attacker" is always a spawned Monster.



Edited by NuclearLavaLamp
Link to comment
Share on other sites

you can get the server via ServerLifecycleHooks.getCurrentServer,
if the game is running (there is a World and you are on server) it will never return null

also note there is a code feature which you can use to post code here

Edited by Luis_ST
  • Like 1
Link to comment
Share on other sites

Please sign in to comment

You will be able to leave a comment after signing in

Sign In Now

  • Create New...

Important Information

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