Saving Prefabs Manually

Discussion and help for Easy Save 3
Post Reply
hefaust
Posts: 4
Joined: Mon Jun 01, 2020 8:26 am

Saving Prefabs Manually

Post by hefaust »

Hello,

I have a problem when I save GameObjects. I save and load GameObjects using ES3Prefab component and it works, but the problem is my prefab hierarchy is large and ES3 saves all components on prefab so my save file becomes huge. Most of that data is unnecessary. I tried to save prefabs data manually, but was unable to load references to other prefabs.

I was testing with simple prefab with component which has public transform field. At runtime I instantiate two of those prefabs A and B. And add reference B to A.
Image

Then I save both of those objects components into separate keys.

Code: Select all

public void Save()
{
    for (var i = 0; i < gameObjects.Length; i++)
    {
        var go = gameObjects[i];
        var es3Prefab = go.GetComponent<ES3Prefab>().prefabId;
        var reference = go.GetComponent<ReferenceToObject_Test>();
        ES3.Save($"PrefabID_{i}", es3Prefab, @"Saves\ReferenceTest.es3");
        ES3.Save($"Transform_{i}", go.transform, @"Saves\ReferenceTest.es3");
        ES3.Save($"Reference_{i}", reference, @"Saves\ReferenceTest.es3");
    }
}
Then I want to instantiate what I have saved. I manually instantiate prefabs and load data into them.

Code: Select all

public void Load()
{
    var keys = ES3.GetKeys(@"Saves\ReferenceTest.es3");
    var prefabKeys = keys.Where(key => key.StartsWith("PrefabID_")).ToArray();
    var transformKeys = keys.Where(key => key.StartsWith("Transform_")).ToArray();
    var referenceKeys = keys.Where(key => key.StartsWith("Reference_")).ToArray();
    
    for (var i = 0; i < prefabKeys.Length; i++)
    {
        var id = ES3.Load<long>(prefabKeys[i], @"Saves\ReferenceTest.es3");
        var prefab = referenceMgr.prefabs.Where(es3Prefab => es3Prefab.prefabId == id)
            .Select(es3Prefab => es3Prefab.gameObject).First();
        var go = Instantiate(prefab);
        ES3.LoadInto(transformKeys[i], @"Saves\ReferenceTest.es3", go.transform);
        ES3.LoadInto(referenceKeys[i], @"Saves\ReferenceTest.es3", go.GetComponent<ReferenceToObject_Test>());
        referenceMgr.Add(go, go.GetInstanceID());
    }
}
But references are not loaded. As I understand it is because saved components ids doesn't exist in the scene.

Is there any possibility to save and load references manually.

User avatar
Joel
Moodkie Staff
Posts: 2971
Joined: Wed Nov 07, 2012 10:32 pm

Re: Saving Prefabs Manually

Post by Joel »

Hi there,

If you are instantiating the prefabs yourself you do not need to maintain reference IDs. You simply need to instantiate the necessary prefabs and then use LoadInto to load the Components into them.

Just to clarify, you shouldn't access the ES3Prefab directly as this is used internally and is unlikely to work as you expect.

All the best,
Joel
Joel @ Moodkie Interactive
Twitter - Unity

Post Reply