如何将参数实现为自定义命令 - Minecraft Forge 1.16.5

How to implement arguments into custom commands - Minecraft Forge 1.16.5

我正在尝试使用 Forge 1.16.5 MDK 在我的 mod 中实现简单的 SetHome 和 Home 命令。我关注了 TutorialsByKaupenjoe 的自定义命令视频 (https://youtu.be/bYH2i-KOLgk) but they didn't describe the use of arguments in commands. I have found very brief and limited descriptions on how to use argument types and even looked at the vanilla commands. The best resource I could find was (https://github.com/TheGreyGhost/MinecraftByExample/blob/master/src/main/java/minecraftbyexample/mbe45_commands/MBEquoteCommand.java)。

这是我的SetHomeCommand.javaclass

package net.caret.goggleutils.commands;

import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.caret.goggleutils.GoggleUtils;
import net.minecraft.command.CommandSource;
import net.minecraft.command.Commands;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.StringTextComponent;

public class SetHomeCommand {
    public SetHomeCommand(CommandDispatcher<CommandSource> dispatcher) {
        dispatcher.register(
                Commands.literal("sethome")
                .then(Commands.argument("number", IntegerArgumentType.integer(1, 10)))
                        .executes(commandContext -> setHome(commandContext.getSource(), IntegerArgumentType.getInteger(commandContext, "number")))
        );
    }

    private int setHome(CommandSource source, int number) throws CommandSyntaxException{
        System.out.println("test");
        ServerPlayerEntity player = source.asPlayer();
        BlockPos playerPos = player.getPosition();
        String pos = "(" + playerPos.getX() + ", " + playerPos.getY() + "," + playerPos.getZ() + ")";

        player.getPersistentData().putIntArray(GoggleUtils.MODID + String.valueOf(number) + "home", new int[]{playerPos.getX(), playerPos.getY(), playerPos.getZ()});

        source.sendFeedback(new StringTextComponent("Set home at " + pos), true);
        return 1;
    }
}

一切正常运行(我还在另一个 class 中订阅了 RegisterCommandsEvent)并且游戏自动完成,但是当我尝试 /sethome 1 我得到

Unknown or incomplete command, see below for error
/sethome 1<--[HERE]

这似乎是构建器链的问题(因为控制台不打印“test”)。

问题是您将 .execute() 放在 .then(Commands.argument(...))

之外

代码的正确部分是:

.then(Commands.argument("number", IntegerArgumentType.integer(1, 10))
                    .executes(commandContext -> setHome(commandContext.getSource(), IntegerArgumentType.getInteger(commandContext, "number")))
    ));

此外,如果您拥有最新的 Forge 1.16.5 MDK,则 setHome 方法中的某些代码可能已过时。 Ej:

  • 'source.asPlayer()' 在新版本中将是 'source.getPlayerOrException()'
  • 'source.sendFeedback() 将是 'source.sendSuccess()'