Choose material from Favorites

Choose material from Favorites

Darren_Fisher
Participant Participant
817 Views
2 Replies
Message 1 of 3

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
Accepted solutions (1)
818 Views
2 Replies
Replies (2)
Message 2 of 3

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

 

Message 3 of 3

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