Ghost Commands
  • Getting Started
    • Quickstart
    • Syntax
      • Command syntax
      • Arguments with multiple values
    • Custom commands
  • Documentation
    • Commands
      • Static commands
      • Non-static commands
      • Dynamic commands
      • Overloads
      • Parameters
      • Additional attributes
    • Suggestions
      • Suggestion attributes
      • Suggestor methods
    • Converters
      • Custom parameter types
      • Using the ArgumentReader
      • Multiple ways to interpret an argument
    • Processors
      • Creating a processor
      • Setting priorities
      • Cheat codes example
    • Macros
    • Settings
    • Customization
    • Included Commands
Powered by GitBook
On this page

Was this helpful?

  1. Documentation
  2. Converters

Multiple ways to interpret an argument

By getting the amount of values with reader.Length, we can support multiple ways to interpret an argument. An example would be how a UnityEngine.Color can be interpreted both from a hex value and an RGB value.

[Converter]
public static Color ColorConverter(ArgumentReader reader)
{
    float r, g, b, a;

    switch (reader.Length)
    {
        // In case the amount of components was 1
        case 1:
            if (reader.IsNumeric())
            {
                // If the component is a number, return an RGB color with this value
                float value = reader.Read<float>() / 255;
                return new(value, value, value);
            }
            else
            {
                // If the component can be read as a string, try to return a color based on a hex value
                string hex = reader.Read<string>();
                if (ColorUtility.TryParseHtmlString(hex, out Color hexColor))
                    return hexColor;
                else
                    throw new Exception($"Invalid hex value: '{hex}'.");
            }

        // In case the amount of components was 3
        case 3:
            // Return an RGB value using the 3 numbers
            r = reader.Read<float>();
            g = reader.Read<float>();
            b = reader.Read<float>();
            return new(r, g, b);

        // In case the amount of components was 4
        case 4:
            // Return an RGBA value using the 4 numbers
            r = reader.Read<float>();
            g = reader.Read<float>();
            b = reader.Read<float>();
            a = reader.Read<float>();
            return new(r, g, b, a);
    }

    // If more or less components was provided, we notify of the error
    throw new Exception($"Could not retrieve color from input: {reader.Source}.");
}

Note

This converter is built-in, and is purely used as an example. You wouldn't need to create this in order to support parameters of type UnityEngine.Color.

PreviousUsing the ArgumentReaderNextProcessors

Last updated 7 months ago

Was this helpful?