Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Question Refactoring properties to be inside a new class, but keeping old assigned values?

Discussion in 'Scripting' started by Senshi, Aug 19, 2020.

  1. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    567
    Hi all,

    Assume I have a serializable class like this:

    Code (CSharp):
    1. class Foo {
    2.     public float a;
    3.     public float b;
    4. }
    And I want to refactor it to something like this:

    Code (CSharp):
    1. class Bar {
    2.     public float a;
    3.     public float b;
    4. }
    5.  
    6. class Foo {
    7.     public Bar bar;
    8. }
    Is there any way I can maintain whatever was assigned to
    a
    and
    b
    in inspector for all objects, ideally as transparently as possible? (I'm thinking something like
    FormerlySerializedAs
    ).

    The reason I'm asking is it's for an asset update, where I'd like to consolidate some variables and functionality so I can use it in a new place as well. However, I absolutely don't want to risk anyone updating losing any work. Any and all ideas would be very much welcome!
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,950
    Rename Foo to Bar (First in Unity, then in your IDE). Your field values should stay the same because the rename preserved the script Asset GUID. Then create a new Foo script.
     
  3. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    567
    Sorry, I appreciate your answer but I may have made my sample a bit too abridged. Foo contains a lot more than just a and b. Unless I'm missing something this solution also wouldn't work for anyone updating my asset through the Store, as that would be a single-step change?
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,950
    Ah ok, I didn't realize this was a published asset in the asset store! Yeah you'll need something more complex possibly. You might need to create a Foo2 and a script that migrates the old data, or something along those lines.
     
  5. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    567
    No worries! I was afraid it'd turn into something hairy like that. In that case I think I may just go with the slightly-less-elegant, lot-less-headaches solution of making Foo extend Bar as much as possible. :p Thanks again for your input!