SanAndreasUnity/Assets/Scripts/Chat/Chat2Commands.cs

52 lines
1.7 KiB
C#
Raw Normal View History

2021-02-20 20:59:29 +00:00
using System;
using SanAndreasUnity.Commands;
using SanAndreasUnity.Net;
using SanAndreasUnity.Utilities;
using UnityEngine;
namespace SanAndreasUnity.Chat
{
public class Chat2Commands : MonoBehaviour
{
private void Start()
{
ChatManager.singleton.RegisterChatPreprocessor(new ChatPreprocessor {processCallback = ProcessChatMessage});
}
private ChatPreprocessorResult ProcessChatMessage(Player player, string chatMessage)
{
if (chatMessage.Length < 2 || !chatMessage.StartsWith("/"))
return new ChatPreprocessorResult { finalChatMessage = chatMessage };
int whiteSpaceIndex = chatMessage.FindIndex(char.IsWhiteSpace);
int commandLength = whiteSpaceIndex < 0 ? chatMessage.Length - 1 : whiteSpaceIndex - 1;
string command = chatMessage.Substring(1, commandLength);
if (!CommandManager.Singleton.HasCommand(command))
return new ChatPreprocessorResult { finalChatMessage = chatMessage };
string fullCommand = chatMessage.Substring(1);
string response;
try
{
response = CommandManager.Singleton.ProcessCommandForPlayer(player, fullCommand).response;
}
catch (Exception exception)
{
response = exception.Message;
}
// send response back to player
2021-02-22 14:48:47 +00:00
if (!string.IsNullOrWhiteSpace(response))
ChatManager.SendChatMessageToPlayer(player, response);
2021-02-20 20:59:29 +00:00
// discard chat message
return new ChatPreprocessorResult {shouldBeDiscarded = true};
}
}
}