Fusion Guide
beginner11 min read

Scripts and Add-Ins Dialog, and Your First Python Script

Use the Scripts and Add-Ins dialog, create a new Python script from the template, understand the generated files and manifest, and run and edit it.

Overview#

The Scripts and Add-Ins dialog is the control centre for the desktop API. It lists the scripts and add-ins Fusion knows about, lets you run and stop them, and has buttons to create new ones from a template, add existing folders, and open them in an editor. This page walks through the dialog, creates a Python script from scratch, explains every generated file, and ends with a more useful script that exports all bodies in a design.

If you have never written code for Fusion, this is the page to follow with the application open next to you.

Where to find it#

  • Utilities tab > Scripts and Add-Ins. The shortcut is Shift+S.
  • The same functionality is available from code through Application.scripts (the Scripts object: createScriptInput, addNew, addExisting, itemByPath, itemsByName).
  • The default folders for scripts and add-ins can be changed in Preferences > General > API.

Scripts and add-ins live in folders on disk. Fusion automatically searches these locations when it starts:

LocationWindowsmacOS
Scripts (default for new scripts)%appdata%\Autodesk\Autodesk Fusion\API\Scripts$HOME/Library/Application Support/Autodesk/Autodesk Fusion/API/Scripts
Add-ins (default for new add-ins)%appdata%\Autodesk\Autodesk Fusion\API\AddIns$HOME/Library/Application Support/Autodesk/Autodesk Fusion/API/AddIns
Autodesk App Store apps (.bundle folders with PackageContents.xml)%appdata%\Autodesk\ApplicationPlugins~/Library/Application Support/Autodesk/ApplicationPlugins
Apps not from the App Store (plain add-in folders, no .bundle needed)%appdata%\Autodesk\FusionAddins~/Library/Application Support/Autodesk/FusionAddins

Autodesk's own topic spells the product folder both Autodesk Fusion and Autodesk Fusion 360 in different sections (an older spelling survives in some paragraphs), so confirm the real path from the Open File Location link in the dialog's details pane. If you change the default folder in Preferences, Fusion searches the Scripts and AddIns folders inside your folder and keeps searching the default location. A script or add-in anywhere else must be linked explicitly (see below).

Step by step#

Part 1: tour the dialog#

Autodesk's help describes two dialog layouts. The current ("new") dialog is the default, and a preference can switch back to the old one. In the current dialog:

  1. Open the dialog. It has three areas: filters on the left (a Browse section with Favorites, All scripts and add-ins, and attribute filters such as Add-ins or Running), the list in the center, and a details pane on the right for the selected item.
  2. Select any item. The details pane shows its properties, including the location on disk (with an Open File Location link), and offers a context menu. The star beside the name marks a favorite.
  3. The list columns are name, running state (the icon also tells you whether the item is a script or an add-in), a Run on Startup check box (add-ins only) and version.
  4. The small toolbar above the list has a + menu (go to the Autodesk App Store, add a Script or add-in from device, or Create script or add-in), an Edit in code editor pencil, an open-folder command and an unlink command (the broken paper clip, for linked items).
  5. Click the run icon beside a script to run it; the dialog closes so the script can work. Click the icon beside an add-in to start it; the dialog stays open, and clicking the icon again stops it.

Part 2: create a new script#

  1. Click the + near the top of the list and choose Create script or add-in.
  2. In the new-app dialog (called New App in the current dialog and Create New Script or Add-In in the old one) fill in:
    • Create a new: Script (the other choice is Add-In).
    • Name: HelloFusion. The name becomes the folder name and the name of the code files. The topic does not state naming rules, so stick to letters, digits and underscores, which also keeps it a valid Python module name.
    • Description and Author: optional; shown in the properties section of the dialog.
    • Programming Language: Python, C++ or TypeScript. (The old dialog could remember your choice with "Save my choice in Preferences".)
    • Run on Startup: add-ins only.
    • Target Operating System: which OS the item should be shown and loaded on.
    • Folder Location: the default is the standard folder, so Fusion lists the item automatically. If you browse to another folder, Fusion creates the item there and also links it.
  3. Click Create. You return to the Scripts and Add-Ins dialog.
  4. The new script appears in the list. Click its run icon.
  5. Expect a message box. The generated Python script (shown below) calls ui.messageBox with the active document name.

Part 3: understand what was generated#

A new Python script produces a folder with the same name as the script:

HelloFusion/
  HelloFusion.py
  HelloFusion.manifest

Add-ins get additional files, covered later. The manifest is a small JSON file with the same base name as the folder. This is the typical manifest shown in the current Autodesk topic (for an add-in; a script uses "type": "script"):

{
    "autodeskProduct": "Fusion",
    "type": "addin",
    "id": "",
    "author": "Roger Rabbit",
    "description": {
        "": "This is my first add-in"
    },
    "version": "",
    "runOnStartup": true,
    "supportedOS": "windows|mac",
    "editEnabled": true,
    "iconFilename": "AddInIcon.svg"
}

Field notes (from Autodesk's description of each key):

  • autodeskProduct "will always have the value Fusion". An older version of the same topic says Fusion360, so manifests created by older releases carry that value.
  • type is addin or script. This is what makes the item one or the other.
  • id "is not used and can be left empty". (The older topic describes it as a GUID that was not yet used but might be later; if you copy an item, give the copy a new GUID in that case.)
  • author is shown in the dialog.
  • description is a JSON object keyed by Microsoft language code; the empty-string key is the default used for any language without its own entry. Codes listed in the topic include 1033 (English), 1031 (German), 1036 (French), 1034 (Spanish), 1040 (Italian), 1041 (Japanese), 1042 (Korean), 1028 (Taiwan Chinese), 2052 (PRC Chinese), 1029 (Czech), 1038 (Hungarian), 1045 (Polish), 1046 (Brazilian Portuguese), 1049 (Russian) and 1055 (Turkish).
  • version is any string, such as 1.0.0, 2016, R1 or V2.
  • runOnStartup is true or false; false is the default and is what you want while developing.
  • supportedOS is windows, mac or windows|mac; on an unsupported OS Fusion neither lists the item nor loads it at startup.
  • sourcewindows and sourcemac appear only in C++ items and name the project file (for example a .vcxproj or .xcodeproj) that Edit opens.
  • editEnabled and iconFilename appear in Autodesk's example manifest but the topic does not describe them. > Note: not confirmed in Autodesk's documentation: their exact behaviour.

The name of the script is not stored in the manifest; it comes from the folder and file names, so renaming means renaming the folder and files.

The Python file Autodesk documents as the generated script template is:

"""This file acts as the main module for this script."""

import traceback
import adsk.core
import adsk.fusion
# import adsk.cam

# Initialize the global variables for the Application and UserInterface objects.
app = adsk.core.Application.get()
ui = app.userInterface


def run(_context: str):
    """This function is called by Fusion when the script is run."""

    try:
        # Your code goes here.
        ui.messageBox(f'"{app.activeDocument.name}" is the active document.')
    except:  # pylint:disable=bare-except
        # Write the error message to the TEXT COMMANDS window.
        app.log(f'Failed:\n{traceback.format_exc()}')

Fusion calls run when the script is executed; once run finishes, the script is done and Fusion unloads it. The context argument carries information such as whether the item is starting with Fusion, which a script can ignore because a script never runs at startup. A script does not need a stop function; add-ins use stop for cleanup, described on the packaging page.

Part 4: edit and rerun#

  1. Select the script and click Edit in code editor (the pencil, or the context menu). For Python, Fusion uses Visual Studio Code. If it is not installed, Fusion shows a dialog offering to install it the first time; repeat the Edit step when the installation finishes. The first time VS Code starts from Fusion it also installs the Microsoft Python extension (ms-python.python).
  2. Change the message to 'Hello, ' + app.userName. Application.userName is the user name of the signed-in Autodesk account.
  3. Save the file. When you run a script, Fusion loads it, runs it, and unloads it, so you do not need to restart Fusion between runs. Add-ins behave differently: they stay loaded, so you must stop and start them to pick up changes.
  4. Run the script again. The new text appears.

Part 5: a more useful script#

This script exports every visible body in the root component as an STL into a folder you choose. It touches the export manager and shows several recurring patterns: the design cast, a loop over a collection, and a folder dialog. It follows the signatures in Autodesk's STL export sample (createSTLExportOptions(geometry, filename)).

import adsk.core, adsk.fusion, traceback, os

def run(context):
    ui = None
    try:
        app = adsk.core.Application.get()
        ui = app.userInterface
        design = adsk.fusion.Design.cast(app.activeProduct)
        if not design:
            ui.messageBox('Switch to the Design workspace first.')
            return

        folder_dlg = ui.createFolderDialog()
        folder_dlg.title = 'Choose export folder'
        if folder_dlg.showDialog() != adsk.core.DialogResults.DialogOK:
            return
        folder = folder_dlg.folder

        export_mgr = design.exportManager
        count = 0
        for body in design.rootComponent.bRepBodies:
            if not body.isVisible:
                continue
            safe_name = ''.join(c if c.isalnum() or c in '-_' else '_' for c in body.name)
            path = os.path.join(folder, safe_name + '.stl')
            opts = export_mgr.createSTLExportOptions(body, path)
            opts.meshRefinement = adsk.fusion.MeshRefinementSettings.MeshRefinementMedium
            export_mgr.execute(opts)
            count += 1

        ui.messageBox(f'Exported {count} bodies to\n{folder}')
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

Points worth noting:

  • ui.createFolderDialog() and ui.createFileDialog() produce native dialogs. Always compare the result of showDialog() with adsk.core.DialogResults.DialogOK.
  • createSTLExportOptions(geometry, filename) accepts a body, an occurrence, or a component as the geometry (Autodesk's sample passes a body, an occurrence and the root component). The STLExportOptions object also has isBinaryFormat, isOneFilePerBody, sendToPrintUtility, surfaceDeviation, normalDeviation, maximumEdgeLength and aspectRatio. Nothing is exported until you pass the options to ExportManager.execute. Note that createSTEPExportOptions takes the file name first (createSTEPExportOptions(filename) or (filename, component)), the reverse of the STL call.
  • The MeshRefinementSettings enumeration (MeshRefinementHigh, MeshRefinementMedium, MeshRefinementLow, MeshRefinementCustom) controls the facet density; MeshRefinementCustom is used together with the deviation and edge-length properties.
  • Names are sanitized because body names may contain characters illegal in file names.
  • Only the root component is walked. For nested components use design.allComponents, or use occurrences and transform for exports in assembled position.

Options reference#

The Create New dialog and manifest have a small set of settings.

OptionWhat it doesNotes/default
Programming LanguagePython, C++ or TypeScriptPython is the most documented; TypeScript is marked experimental in the help
Create a newScript or Add-InWrites type into the manifest
NameFolder and code-file nameThe manifest does not store the name
Description / AuthorShown in the properties paneStored in the manifest
VersionOptional version label (add-ins)Any string, for example 1.0.0
Run on StartupStarts an add-in when Fusion startsAdd-ins only; check box in dialog and runOnStartup in manifest; leave off while debugging
Target Operating SystemWindows, Mac or bothsupportedOS in the manifest
Folder LocationWhere the item is createdDefaults to the standard folder; other folders are created and linked
Run iconRuns a script or starts an add-inScripts end by themselves; add-ins stay loaded; a running add-in's icon stops it
Edit in code editorOpens the item in its editorVS Code for Python and TypeScript; the project file named in sourcewindows/sourcemac for C++
Debug (old dialog's Run drop-down)Same as EditAutodesk says there is no reason to use it; debugging starts from VS Code
Script or add-in from deviceLinks an existing folderLets you develop outside the default folders
UnlinkRemoves a linkDoes not delete the folder

Tips and pitfalls#

Tip: Develop in a folder of your choice (such as a Git repository) and use the Script or add-in from device option in the + menu to link it. Fusion remembers the link; Unlink removes it from the list without deleting the folder. You avoid editing inside the Autodesk application-support directory and can put your work under version control.

Tip: Keep the template try/except block. Without it, an exception can disappear silently or produce a terse generic failure.

Warning: The folder, the main code file and the .manifest file share the item's name. Autodesk's topic says to change all of them to rename an item.

Warning: General Python advice, not Autodesk data: do not name your script file after a standard library or Fusion module (random.py, adsk.py, json.py), because Python may import yours instead.

Warning: Python runs inside Fusion on the main Fusion thread, so while your script runs most of Fusion appears frozen and model changes are not drawn until it finishes. Autodesk's Python topic suggests adsk.doEvents() to give Fusion a chance to process queued messages, for example inside a loop that adds geometry. Do not call Fusion API functions from your own worker threads; the Threading topic says even messageBox from a worker can crash Fusion and describes custom events as the safe route (see the event handlers page).

Practice exercise#

  1. Create a script named BodyReport.
  2. In run, get the active design and loop over design.rootComponent.bRepBodies.
  3. Build a string with each body's name and its volume in cubic centimetres (body.volume, which is in cm^3), then display it in a message box.
  4. Add a check so that if the root component has no bodies, it says so.

Expected result: a message listing each body with a volume figure consistent with Fusion's Properties dialog (convert units: 1 cm^3 = 1000 mm^3).

  • Fusion API overview
  • API object model
  • Debugging in VS Code
  • Packaging and distributing add-ins

Sources

Checked against these Autodesk help topics (opens autodesk.com):

Related pages