Sunday, 29 March 2015

optionVar and global variables in mel

Option variables are a way of storing data in maya between sessions. Most of your preferences are saved in this way. Global variables are a way of making information available between scripts on a per session basis. Say you wanted to know how many times a function had run, but keep the total between sessions. You could store that number as an optionVar. That way the total would persist between maya sessions.




At the bottom of the post are some demo scripts, copy them into your script editor and execute them. Then to see the counter going, run countingFunction; 
You will see some debug text in the output window;
times pressed this session 2
times pressed forever 18

To reset the count for the current session run resetSession;

The key elements here are intialising the optionVar. ,
   if (`optionVar -exists "myVar"`)  
   {  
     $returnVal = `optionVar -query "myVar"`; //If the optionVar exists then return the value  
   } else optionVar -intValue "myVar" 0; //If the optionVar doesn't exists then make one  

The current session count is held in the global variable named global int $countingFunctionVal; If this variable is declared within any other script, the current value will be available to that procedure. Many of Maya's main UI elements are declared as global variables in this way so items such as the graph editor, channelbox and time slider can be accessed easily.


The demo scripts:

 global proc int countingFunctionTotal()  
 {  
   int $returnVal;  
   if (`optionVar -exists "runCount"`)  
   {  
     $returnVal = `optionVar -query "runCount"`;  
   }  
   return $returnVal;  
 }  
 global proc int countingFunctionAdd()  
 {  
   //if optionVar -iv "runCount" 4 -sv "defaultFileName" "buffalo.maya";  
   int $returnVal;  
   if (`optionVar -exists "runCount"`)  
   {  
     $returnVal = `optionVar -query "runCount"`;  
     $returnVal ++;  
     optionVar -intValue "runCount" $returnVal;  
   } else optionVar -intValue "runCount" 1;  
   return $returnVal;  
 }  
 global proc countingFunction()  
 {  
   global int $countingFunctionVal;  
   int $totalCound = `countingFunctionAdd`;  
   $countingFunctionVal++;  
   print ("times pressed this session " + $countingFunctionVal + "\ntimes pressed forever " + $totalCound +"\n");  
 }  
 global proc resetSession()  
 {  
   global int $countingFunctionVal;  
   $countingFunctionVal = 0;  
 }  

No comments:

Post a Comment