This is the (Rust only) code that I use to match players, it uses the active player list to try to make an exact match first and then falls back to a partial match, also included an example on how to use it in your case:
#region Example usage
[ChatCommand("test")]
private void testChatCommand(BasePlayer player, string command, string[] args)
{
if (args.Length == 0)
{
SendReply(player, $"Usage:{Environment.NewLine}/test PlayerName");
return;
}
BasePlayer target;
try
{
target = FindPlayerByName(String.Join(" ", args));
}
catch (AmbiguousPlayerMatch matchError)
{
SendReply(player, $"There was an error trying to find the specified player:{Environment.NewLine}{matchError.Message}");
return;
}
SendReply(player, $"Player {target.IPlayer.Name} has {target.Health()} hp.");
SendReply(target, $"Player {player.IPlayer.Name} just checked your health.");
}
#endregion
#region Find Players
private static BasePlayer FindPlayerByName(string name)
{
// Try to get an exact case sensitive match
BasePlayer[] targetPlayers = BasePlayer.activePlayerList.Where(p => p.IPlayer?.Name == name).ToArray();
// If no match was found, try a partial case insensitive match
if (targetPlayers.Length == 0)
targetPlayers = BasePlayer.activePlayerList.Where(p => p.IPlayer?.Name.ToLower().Contains(name.ToLower()) == true).ToArray();
// If no perfect match was found, complain
if (targetPlayers.Length != 1)
throw new AmbiguousPlayerMatch(name, targetPlayers);
return targetPlayers[0];
}
private static BasePlayer[] FindPlayersByName(string name)
{
// Try to get an exact case sensitive match
BasePlayer[] targetPlayers = BasePlayer.activePlayerList.Where(p => p.IPlayer?.Name == name).ToArray();
// If no match was found, try a partial case insensitive match
if (targetPlayers.Length == 0)
targetPlayers = BasePlayer.activePlayerList.Where(p => p.IPlayer?.Name.ToLower().Contains(name.ToLower()) == true).ToArray();
// If no match was found, complain
if (targetPlayers.Length == 0)
throw new AmbiguousPlayerMatch(name, targetPlayers);
return targetPlayers;
}
class AmbiguousPlayerMatch : Exception
{
public string Name { get; private set; }
public BasePlayer[] Matches { get; private set; }
public AmbiguousPlayerMatch(string name, BasePlayer[] matches)
: base($"Found {matches.Length} players matching \"{name}\"{(matches.Length == 0 ? "." : $", please be more specific:{Environment.NewLine}{String.Join(Environment.NewLine, matches.Select(p => $"Matches: {p.IPlayer?.Name}"))}")}")
{
this.Name = name;
this.Matches = matches;
}
}
#endregion