Search Unity

Updating a prefab in script

Discussion in 'Prefabs' started by eekllc, Jan 30, 2019.

  1. eekllc

    eekllc

    Joined:
    Dec 14, 2009
    Posts:
    19
    I'm hoping somebody can help me out with migrating to using the new Prefab system via script.

    I upgraded my project to Unity 2018.3 with the new prefab system, and it broke some code. I'm having a hard time figuring out the new way to do this seemingly simple task. For reference, here's the old code that worked fine in 2018.2:

    Code (CSharp):
    1. var chars = Resources.FindObjectsOfTypeAll<CharacterStory>().Where(c => c.Data.StoryName == me.Data.StoryName);
    2.     foreach (var item in chars)
    3.     {
    4.         item.Data.Clear();
    5.         SerializationManager.Instance.JsonDeserializeFromFile(ref item.Data, Encoding.Unicode, path, item.Data.CharacterName, "character");
    6.     }
    7.  
    This used to work just fine and it found my prefabs of the stories in the project view, and my changes updated the prefab. Now, it seems this defaults to giving me an instance of the prefab and I need to now apply those changes back to the parent object in order for my changes to stick? I'm just not sure exactly how to do that.
     
  2. eekllc

    eekllc

    Joined:
    Dec 14, 2009
    Posts:
    19
    Actually, just figured this out. For anybody else looking for the answer, here's how to do it in 2018.3:

    Code (CSharp):
    1.  
    2. var chars = Resources.FindObjectsOfTypeAll<CharacterStory>().Where(c => c.Data.StoryName == me.Data.StoryName);
    3.  
    4. foreach (var item in chars)
    5. {
    6.     if (PrefabUtility.IsPartOfPrefabAsset(item))
    7.     {
    8.          var prefabPath = AssetDatabase.GetAssetPath(item);
    9.          var prefabRoot = PrefabUtility.LoadPrefabContents(prefabPath);
    10.  
    11.           var story = prefabRoot.GetComponent<CharacterStory>();
    12.           story.Data.Clear();
    13.           SerializationManager.Instance.JsonDeserializeFromFile(ref story.Data, Encoding.Unicode, path, item.Data.CharacterName, "character");
    14.  
    15.            PrefabUtility.SaveAsPrefabAsset(prefabRoot, prefabPath);
    16.            PrefabUtility.UnloadPrefabContents(prefabRoot);
    17.         }
    18.     }
    19. }
    20.