主要插件類別

備註

阅读 Sponge 文档中的所有内容都建立在你已经事先掌握了 Java 知识的基础上。SpongeAPI 提供了你开始为使用 Sponge 的 Minecraft 服务器开发插件的基础。然而,让你的代码工作和富有创新取决于你!有一些免费的在线 Java 课程可以帮助你,如果你在 Java 方面实在没什么经验。

新建你自己的类

在添加一个 SpongeAPI 作为依赖后的下一步自然就是新建一个类。这个类可以按照你想要的方式去命名,而且可以使用除了 org.spongepowered 外的任何一个包。按照惯例,一个类的名称应该首字母大写。

Oracle 推荐 你去使用你自己的域名作为你的包名,如果你有这样的一个域名的话。然而,如果你没有拥有一个域名,一种常见的做法是使用一个电子邮件(如 com.gmail.username.project),或者一个开源仓库的地址(如 io.github.username.project)。

当你创建好你的主类后,你的主类必须有 Plugin 这个注解(Annotation)。这个注解能够让 Sponge 在读取插件时找到你的主类。下面是一个详细解释 插件中繼資料 用法的示例。

package io.github.username.project;

import org.spongepowered.plugin.builtin.jvm.Plugin;

@Plugin("exampleplugin")
public class ExamplePlugin {

}

備註

如果你还没有选择好一个插件 ID,可以看看这一部分: 插件識別碼

初始化你的插件

Your plugin can listen for particular events, called lifecycle events, to be notified about changes in the state of the game or be to prompted to peform a specific task, such as registering a command. In the example below, onServerStart(StartedEngineEvent<Server>) is called when the StartedEngineEvent occurs for the Server. Note that the method is annotated with the Listener annotation.

下列示例会在服务器启动时打印一条信息。如果你的插件正确加载了,你会在服务器的初始化输出中找到这条信息。

import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.lifecycle.StartedEngineEvent;
import org.spongepowered.plugin.builtin.jvm.Plugin;

// Imports for logger
import com.google.inject.Inject;
import org.apache.logging.log4j.Logger;

@Plugin("exampleplugin")
public class ExamplePlugin {

    @Inject
    private Logger logger;

    @Listener
    public void onServerStart(final StartedEngineEvent<Server> event) {
        logger.info("Successfully running ExamplePlugin!!!");
    }

}

小訣竅

The Sponge documentation provides a guide with more information on events (see 事件). Normally, in addition to prefixing event-handler methods with @Listener, you must also register your object with Sponge’s event bus, which can be done at any time. However, your main plugin class is registered automatically.

Lifecycle Events

It may also be desirable to listen for other lifecycle events in your plugin, such that you can react to re-registration requests or engine/game state changes. See the plugin lifecycle documentation for more information on the lifecycle events available for plugins to listen to.