您最多选择25个主题 主题必须以中文或者字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

108 行
3.1 KiB

using System;
using UnityEngine;
using System.Linq;
namespace UnityConsole
{
/// <summary>
/// The behavior of the console.
/// </summary>
[DisallowMultipleComponent]
[RequireComponent(typeof(ConsoleController))]
public class ConsoleController : MonoBehaviour
{
public static ConsoleController Instance { get; private set; }
private const int inputHistoryCapacity = 20;
public ConsoleUI ui;
public KeyCode toggleKey = KeyCode.BackQuote;
public bool closeOnEscape = false;
private ConsoleInputHistory inputHistory = new ConsoleInputHistory(inputHistoryCapacity);
private void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(this);
}
else
{
Instance = this;
}
}
void OnEnable()
{
ui.onSubmitCommand += ExecuteCommand;
ui.onClearConsole += inputHistory.Clear;
}
void OnDisable()
{
ui.onSubmitCommand -= ExecuteCommand;
ui.onClearConsole -= inputHistory.Clear;
}
void Update()
{
if (Input.GetKeyDown(toggleKey))
{
ui.ToggleConsole();
}
if (!ui.isConsoleOpen)
{
return;
}
if (Input.GetKeyDown(KeyCode.Escape) && closeOnEscape)
{
ui.CloseConsole();
}
else if (Input.GetKeyDown(KeyCode.UpArrow))
{
NavigateInputHistory(true);
}
else if (Input.GetKeyDown(KeyCode.DownArrow))
{
NavigateInputHistory(false);
}
else if (Input.GetKeyDown(KeyCode.Tab))
{
ui.TabComplete();
}
}
private void NavigateInputHistory(bool up)
{
string navigatedToInput = inputHistory.Navigate(up);
ui.SetInputText(navigatedToInput);
}
private void ExecuteCommand(string input)
{
char[] split = new char[] {' '};
string[] parts = input.Split(split, StringSplitOptions.RemoveEmptyEntries);
string command = parts[0];
string[] args = parts.Skip(1).ToArray();
ui.AddNewOutputLine("> " + input);
ConsoleCommandResult consoleCommandResult = ConsoleCommandsDatabase.ExecuteCommand(command, args);
ui.AddNewOutputLine(consoleCommandResult.succeeded ? "Done" : "Failed");
if (!consoleCommandResult.succeeded && !string.IsNullOrEmpty(consoleCommandResult.Output))
{
Debug.LogError(consoleCommandResult.Output);
}
if (!string.IsNullOrEmpty(consoleCommandResult.Output))
{
ui.AddNewOutputLine(consoleCommandResult.Output);
}
inputHistory.AddNewInputEntry(input);
}
}
}