View Full Version : If Nothing is selected

12 December 2007, 02:25 AM
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

$.material = meditMaterials[1]


12 December 2007, 02:33 AM
If nothing is selected, $ returns undefined. So you can test for 'undefined' and not do anything in that case.

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

12 December 2007, 03:56 AM
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.

12 December 2007, 07:03 AM
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]

12 December 2007, 08:37 AM
even better, you could use your original code and only change the line:
$.material = meditMaterials[1]
selection.material = meditMaterials[1]

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

12 December 2007, 09:58 AM
this is true... even faster (and easier to read).

12 December 2007, 09:42 PM
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!

CGTalk Moderation
12 December 2007, 09:42 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.