Announcements
Autodesk Community will be read-only between April 26 and April 27 as we complete essential maintenance. We will remove this banner once completed. Thanks for your understanding

Choose material from Favorites

Darren_Fisher
Participant

Choose material from Favorites

Darren_Fisher
Participant
Participant

Hello,

 

I trying to pick a material stored in my 'Favorites' and assign to a body but get the error shown in the pic.

I've used the following code, and worked fine when picking from the 'Fusion 360 Material Library'

 

# get material lib
mLibs = app.materialLibraries
mLib = mLibs.itemByName('Favorites')
# get one material from this lib
mOne = mLib.materials.itemByName('AB2')

. . . .

BladeLoftBody = BladeLoft.bodies.item(0)

. . . .

bodyM = BladeLoftBody.material

# change body material
BladeLoftBody.material = mOne
app.activeViewport.refresh()

 

Many Thanks in advance.

Error and material shown in FavoritesError and material shown in Favorites

 

0 Likes
Reply
Accepted solutions (1)
616 Views
2 Replies
Replies (2)

JeromeBriot
Mentor
Mentor
Accepted solution

Hello,

 

the error message says that the object mLib is empty (None). You should always test the returned value when accessing an item of a collections. For example:

import adsk.core, traceback

def run(context):

    ui = None

    try:

        app = adsk.core.Application.get()
        ui  = app.userInterface

        materialLibrary = 'Favorite'

        mLibs = app.materialLibraries

        mLib = mLibs.itemByName(materialLibrary)

        if mLib is None:
            ui.messageBox('Material "{}" not found.'.format(materialLibrary))
            return

    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

To solve your problem, replace:

 

mLib = mLibs.itemByName('Favorites')

with:

 

mLib = mLibs.itemByName('Favorites Library')

 

Here is a code to list all material libraries by name:

 

import adsk.core, traceback

def run(context):

    ui = None

    try:

        app = adsk.core.Application.get()
        ui  = app.userInterface

        mLibs = app.materialLibraries

        for mLib in mLibs:
            print(mLib.name)

    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

You can use the same approach with any collections when you need to get a specific item by name.

 

Hope this helps

 

1 Like

Darren_Fisher
Participant
Participant

Fantastic thanks for the help, its working perfectly now.

Just starting out in the API area so will no doupt have many more questions.

0 Likes