Author Topic: [Snippet] Simple Console Commands handler  (Read 35 times)

LittleCodingFox

  • Newbie
  • *
  • Posts: 2
    • View Profile
[Snippet] Simple Console Commands handler
« on: November 02, 2020, 12:44:38 AM »
Here's a simple way of handling  custom console commands

You can declare a console command handler interface in a new script:

Code
    public interface IVoxelPlayCommandHandler
    {
        VoxelPlayFirstPersonController owner { get; set; }

        bool HandlesCommand(string name);
        void HandleCommand(string name, string[] parameters);
    }

Then you can make new commands using this interface:

Code
    public class PlaceVoxelsConsoleCommand : IVoxelPlayCommandHandler
    {
        public BamomakiFirstPersonController owner { get; set; }

        public void HandleCommand(string name, string[] parameters)
        {
            if(parameters.Length != 7 || !int.TryParse(parameters[1], out var x) ||
                !int.TryParse(parameters[2], out var y) || !int.TryParse(parameters[3], out var z) ||
                !int.TryParse(parameters[4], out var width) || !int.TryParse(parameters[5], out var height) ||
                !int.TryParse(parameters[6], out var depth))
            {
                VoxelPlayUI.instance.AddConsoleText("Syntax: placevoxel name x y z width height depth");

                return;
            }

            var voxelType = owner.env.GetVoxelDefinition(parameters[0]);

            if(voxelType == null)
            {
                VoxelPlayUI.instance.AddConsoleText($"Voxel type not found: '{parameters[0]}'");

                return;
            }

            VoxelPlayEnvironment.instance.VoxelPlace(new Vector3(x, y, z), new Vector3(x + width, y + height - 1, z + depth), voxelType, Color.white);
        }

        public bool HandlesCommand(string name)
        {
            return name == "placevoxel";
        }
    }

Please notice you need an array of IVoxelPlayCommandHandler for the command handlers

Finally, to use these commands you need to subscribe to the console comand event in Voxel Play:

Code
...

            foreach (var handler in commandHandlers)
            {
                handler.owner = this;
            }

            VoxelPlayUI.instance.OnConsoleNewCommand += OnConsoleNewCommand;

...

Code
        private void OnConsoleNewCommand(string text)
        {
            var pieces = text.Split(" ".ToCharArray());

            if(pieces.Length == 0)
            {
                return;
            }

            var command = pieces.FirstOrDefault().Substring(1);
            var parameters = pieces.Skip(1).ToArray();

            foreach(var handler in commandHandlers)
            {
                if(handler.HandlesCommand(command))
                {
                    handler.HandleCommand(command, parameters);

                    return;
                }
            }
        }