Skip to content

Development

oldnapalm edited this page Dec 14, 2024 · 2 revisions

Writing a plugin

This guide will help you get started with writing plugins for the server.

Requirements

  • Visual Studio 2022 (or .NET CLI)
  • Experience with C#/.NET

Setup

public class Example : IPlugin
{
    public string Name => "Example";

    public string Description => "An example plugin for demonstrating the plugin API";

    public string Author => "TheIndra";

    public bool OnEnable(GameServer gameServer, bool isAfterServerLoad) { return true; }
}

The OnEnable method will be called as soon as the plugin is loaded, the plugin can return false here when it failed to initialize.

Commands

Plugins can register commands, these can be executed by both the server and clients. You can register a command by adding the Command attribute to a method.

[Command("hello")]
public static void Hello(CommandContext ctx, List<string> args)
{
    if (ctx.Sender is ConsoleCommandSender)
    {
        ctx.SendMessage("You cannot execute this command as console.");
        return;
    }

    ctx.SendMessage("Hello, World!");
    ctx.Client.Position = new Vector3(293.08f, 180.46f, 104.3f);
}

Two arguments are passed CommandContext and List<string>. The command context contains all context of the command such as the GameServer instance, sender and orginal message. The other is a list of arguments which were passed to the command.

To register all commands in a class use gameServer.RegisterCommands<ExampleCommands>() in your OnEnable, where ExampleCommands is the class containing all commands.

Hooks

A plugin can register hooks to get notified about events, for this you can use the ConnectionEvents, GameEvents and PacketEvents classes. Some require you to return a PluginResponse with the ability to modify the orginal context passed to other plugins and the server.

public bool OnEnable(GameServer gameServer, bool isAfterServerLoad)
{
    ConnectionEvents.OnConnectionRequest.Add(ConnectionRequest);

    return true;
}

private PluginResponse<ConnectionRequest> ConnectionRequest(Client client, ConnectionRequest request)
{
    // Modify the connection request
    request.DisplayName = "Player" + new Random().Next(5, 10);

    return new PluginResponse<ConnectionRequest>
    {
        // Setting 'ContinueServerProc' to false tells the server to not continue processing this connection
        ContinueServerProc = true,
        ContinuePluginProc = true,
        // Pass the connection request object to the plugin response
        Data = request
    };
}
Clone this wiki locally