I recently saw CS2 console and decided to improve my own console. I am trying to use a Dictionary to autocomplete all available commands i.e. typing “s” would display “survey”,”skills”,”slow”
Commands and Dictionary are added to a list.
private void Awake()
{
devConsole = GetComponent<DevConsole>();
CreateConsoleCommands();
}
void CreateConsoleCommands()
{
AllCommands = new List<DevCommands>();
SearchCommand = new Dictionary<string,DevCommands>();
string CommandName = "help";
DevCommands Help = new DevCommands(CommandName, "Shows all commands.", () =>
{
foreach (var item in AllCommands)
{
DefaultLog(item.Name + ": " + item.Description);
}
});
AllCommands.Add(Help);
SearchCommand.Add(CommandName, Help);
CommandName = "clear";
DevCommands Clear = new DevCommands(CommandName, "Clears the console", () =>
{
ConsoleLogText.text = string.Empty;
});
AllCommands.Add(Clear);
SearchCommand.Add("clear", Clear);
CommandName = "spawn";
DevCommands Spawn = new DevCommands(CommandName, "spawns items ", () =>
{
if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("GAME"))
{
SpawnProps.SpawnAll();
DefaultLog("Spawned more props.");
}
else
{
DefaultLog("Cannot be used in the main menu.", LogType.Warning);
}
});
AllCommands.Add(Spawn);
SearchCommand.Add(CommandName, Spawn);
I have tried a dictonary but that dosen’t seem to include partial search.
void SearchForDevCommand(string text)
{
if (SearchCommand.TryGetValue(ConsoleInputField.text,out DevCommands command))
{
Debug.Log(command.Name);
}
else
{
Debug.Log("Can't find any command.");
}
}
Your SearchCommand
dictionary is only good for the final exact access!
As a simple solution for the search you rather want to use e.g. StartsWith
and use it as a filter like e.g.
List<DevCommands> SearchForDevCommand(string text)
{
return AllCommands.Where(c => c.Name.StartsWith(text, StringComparison.InvariantCultureIgnoreCase)).ToList();
// basically same as doing
//var results = new List<DevCommands>();
//foreach(var c in AllCommands)
//{
// if(c.Name.StartsWith(text, StringComparison.InvariantCultureIgnoreCase))
// {
// results.Add(c);
// }
//}
//
//return results;
}
See
- Linq
Where
(using System.Linq;
) string.StartsWith
Does this answer your question? How to create a trie in c#
Or this? stackoverflow.com/a/45510143/106159