Notifications
Clear all

[Closed] If Nothing is selected

What would be the command to have a script stop if no object is selected?

I have a script where a material will assign to the selected object, but the script errors if no object is selected. What would be the command to fix this?

checkbox forSelected “Add Material to selected object/s” pos:[90, 80] bgcolor:[40,2,20]
button butDefault “Create Default Material” pos:[90, 120]

on butDefault pressed do
(

        meditMaterials[1] = VRayMtl ()
        
        if forSelected.checked == true
            
            
                then
        (
            $.material = meditMaterials[1]
            )
            else()
                    
        
    )
6 Replies

If nothing is selected, $ returns undefined. So you can test for ‘undefined’ and not do anything in that case.

if $ != undefined do ( /* your code */ )

Alternatively, you can check the selection.count . If selection.count == 0 then nothing is selected. The good thing about selection, rather than $, is that selection is an array/collection so it will always have properties such as .count even if it is empty, whereas if nothing is selected $ is undefined (as scorpion points out) so you will error if you try to access a property (such as count). For example, if you need two objects selected, you would use “if selection.count == 2” rather than “if $.count == 2”, as the latter would return an error as $ is undefined. Just some extra info.

Actually, using selection with a for loop, you don’t need to test count or anything because the loop won’t be run if the array is empty so you get:


on butDefault pressed do (
    meditMaterials[1] = VRayMtl()

    if forSelected.checked then
        for obj in selection do
            obj.material = meditMaterials[1]
)

even better, you could use your original code and only change the line:
$.material = meditMaterials[1]
to
selection.material = meditMaterials[1]

this would work potentially faster than a for loop since it’s a mapped function

this is true… even faster (and easier to read).

Wow thanks for the replies guys! I just read the replies and Im about to put them to the test, thanks for the prompt response. Will reply with my results soon!

—update. Awesome! That works! Thanks a lot guys! I simple changed $.material to selection.material and it no longer gives me an error message. Thanks!