Search Unity

Best way to refactor public script properties?

Discussion in 'Scripting' started by toomas, May 25, 2012.

  1. toomas

    toomas

    Joined:
    Jun 19, 2009
    Posts:
    16
    Hi all,
    I am wondering how do you handle the case when you need to change the name of public property of MonoBehaviour without having to reassign references manually?

    So far I've done it manually, but now I have a complex NGUI built and it's becoming tedious to go over all the elements that use, say, my custom UIFill script which needs a property name change.
     
  2. superpig

    superpig

    Drink more water! Unity Technologies

    Joined:
    Jan 16, 2011
    Posts:
    4,657
    Create the new field without removing the old one, then write an editor script to go through all your objects and assign the old value to the new field. Then remove the old field.

    Make backup copies / VCS checkins prior to all of this, of course...
     
  3. toomas

    toomas

    Joined:
    Jun 19, 2009
    Posts:
    16
    Thanks for the quick reply! :)

    Here's the way I resolved it, for others who might need to do the same thing:
    1. add newProp property
    2. add this snippet temporarily to that class and edit it.
    Code (csharp):
    1.  
    2.     [ContextMenu("Refactor")]
    3.     void Refactor() {
    4.         var cs = FindSceneObjectsOfType(GetType()) as UIButtonStates[];
    5.         foreach(var c in cs)
    6.         {
    7.             c.newProp = c.oldProp;
    8.         }
    9.     }
    10.  
    3. right click in Inspector and "Refactor"
    4. verify that it did what expected, update your script to use newProp and remove oldProp and code snippet
     
    Last edited: May 25, 2012