feat: add console command attributes

This commit is contained in:
Roflmuffin
2023-10-12 23:49:59 +10:00
parent c25c4f068b
commit 0f7d11f4d2
4 changed files with 45 additions and 1 deletions

View File

@@ -0,0 +1,17 @@
using System;
using CounterStrikeSharp.API.Modules.Events;
namespace CounterStrikeSharp.API.Core.Attributes;
[AttributeUsage(AttributeTargets.Method)]
public class ConsoleCommandAttribute : Attribute
{
public string Command { get; }
public string Description { get; }
public ConsoleCommandAttribute(string command, string description = null)
{
Command = command;
Description = description;
}
}

View File

@@ -321,6 +321,12 @@ namespace CounterStrikeSharp.API.Core
remove => RemoveListener("OnEntityDeleted", value);
}
public void RegisterAllAttributes(object instance)
{
this.RegisterAttributeHandlers(instance);
this.RegisterConsoleCommandAttributeHandlers(instance);
}
/**
* Automatically registers all game event handlers that are decorated with the [GameEventHandler] attribute.
*/
@@ -349,6 +355,20 @@ namespace CounterStrikeSharp.API.Core
}
}
public void RegisterConsoleCommandAttributeHandlers(object instance)
{
var eventHandlers = instance.GetType()
.GetMethods()
.Where(method => method.GetCustomAttribute<ConsoleCommandAttribute>() != null)
.ToArray();
foreach (var eventHandler in eventHandlers)
{
var commandInfo = eventHandler.GetCustomAttribute<ConsoleCommandAttribute>();
AddCommand(commandInfo.Command, commandInfo.Description, eventHandler.CreateDelegate<CommandInfo.CommandCallback>(instance));
}
}
public void Dispose()
{
Dispose(true);

View File

@@ -67,7 +67,7 @@ namespace CounterStrikeSharp.API.Core
Console.WriteLine($"Loading plugin: {pluginType.Name}");
_plugin = (BasePlugin)Activator.CreateInstance(pluginType)!;
_plugin.RegisterAttributeHandlers(_plugin);
_plugin.RegisterAllAttributes(_plugin);
_plugin.Load(hotReload);
Console.WriteLine($"Finished loading plugin: {Name}");

View File

@@ -20,6 +20,7 @@ using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Events;
namespace TestPlugin
@@ -65,6 +66,12 @@ namespace TestPlugin
Console.ResetColor();
}
[ConsoleCommand("cssharp_attribute", "This is a custom attribute event")]
public void OnCommand(int client, CommandInfo command)
{
Console.WriteLine("cssharp_attribute called!");
}
private void GenericEventHandler<T>(T @event) where T : GameEvent
{
Console.BackgroundColor = ConsoleColor.Blue;