[TIP] Getting Units Settings Via the API

Getting Units Settings Via the API

The API OptionsProvider for "UnitsOptions" has interdependent options that do not always return values that we would expect.

“In a nutshell”, when the 'LengthFormat' option is set to any other format option than Length::Decimal, the LengthUnit, AreaUnit and VolumeUnit options do not return actual values.

This means you must use custom methods in your extension(s) to get the correct value.

Length:

def get_unit_length
  opts = Sketchup.active_model.options['UnitsOptions']
  format = opts['LengthFormat']
  case format
  when Length::Decimal
    opts['LengthUnit']
  when Length::Engineering
    Length::Feet
  when Length::Architectural, Length::Fractional
    Length::Inches
  else
    -1 # unknown format
  end
end

Area:

def get_unit_area
  opts = Sketchup.active_model.options['UnitsOptions']
  format = opts['LengthFormat']
  case format
  when Length::Decimal
    opts['AreaUnit']
  when Length::Architectural, Length::Engineering
    Length::SquareFeet
  when Length::Fractional
    Length::SquareInches
  else
    -1 # unknown format
  end
end

Volume:

def get_unit_volume
  opts = Sketchup.active_model.options['UnitsOptions']
  format = opts['LengthFormat']
  case format
  when Length::Decimal
    opts['VolumeUnit']
  when Length::Architectural, Length::Engineering
    Length::CubicFeet
  when Length::Fractional
    Length::CubicInches
  else
    -1 # unknown format
  end
end
2 Likes