Saving, Loading and Instantiating Prefabs

Easy Save 2 has been replaced by Easy Save 3, so is no longer supported.
Locked
User avatar
Joel
Moodkie Staff
Posts: 4810
Joined: Wed Nov 07, 2012 10:32 pm

Saving, Loading and Instantiating Prefabs

Post by Joel »

Saving, Loading and Instantiating Prefabs

In this example, we create a script which saves and loads prefabs.

The main functions we use in this example are:

Code: Select all

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class InstantiatePrefab : MonoBehaviour 
{
	// This is the prefab that we want to instantiate.
	public GameObject prefab;
	// This is a list of the prefabs that we've created and want to save.
	public List<GameObject> createdPrefabs = new List<GameObject>();
	// This is the file which Easy Save will create to save our data.
	public string saveFile = "myPrefabs.txt";
	
	/*
	 * This is where we'll LOAD and create our prefabs.
	 */
	void Start () 
	{
		// If our save file doesn't exist, there are no prefabs to load.
		if(!ES2.Exists(saveFile))
			return;
		
		// Load the number of prefabs we need to instantiate.
		int prefabCount = ES2.Load<int>(saveFile+"?tag=prefabCount");
		
		// For each prefab that we need to load ...
		for(int i=0; i<prefabCount; i++)
		{
			// Create a new instance of the prefab.
			GameObject newPrefab = Instantiate (prefab) as GameObject;
			
			// Load the Transform for that particular prefab using the
			// ES2 self-assigning Load.
			ES2.Load<Transform>(saveFile+"?tag="+i, newPrefab.transform);
			
			// Add the GameObject to the list.
			createdPrefabs.Add(newPrefab);
		}
	}
	
	/*
	 * This is where we'll SAVE our prefabs.
	 * Note that OnApplicationQuit() isn't called on mobile devices.
	 * OnApplicationPause(bool) should be used on mobile devices instead.
	 */
	void OnApplicationQuit () 
	{
		// Save the number of prefabs we're saving.
		ES2.Save (createdPrefabs.Count, saveFile+"?tag=prefabCount");
		
		// Now save the Transform of each created prefab,
		// using the order in the list as the tag.
		for(int i=0; i<createdPrefabs.Count; i++)
			ES2.Save(createdPrefabs[i].transform, saveFile+"?tag="+i);
	}
}
whendricso
Posts: 1
Joined: Sat Jun 08, 2013 11:10 pm

Re: Saving, Loading and Instantiating Prefabs

Post by whendricso »

This only allows you to save a single prefab.

I am trying to save large lists of multiple prefabs. The code here saves a single prefab fine but when I try to load multiple prefabs, it does not save the Transform correctly, only the position rotation and scale are saved but not the entire transform component.

Code: Select all

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
 
public class PrefabMemory : MonoBehaviour
{
	public GameObject[] fabs;
	// This is a list of the prefabs that we've created and want to save.
	public List<GameObject> createdPrefabs = new List<GameObject> ();
	// This is the file which Easy Save will create to save our data.
	public string saveFile = "myPrefabs.txt";
    
	void Start() {
		foreach (GameObject pFab in fabs) {
			Debug.Log("Prefab tag: " + pFab.tag);
		}
	}
	
	void Update() {
		//save
		if (Input.GetKeyDown(KeyCode.K)) {
			createdPrefabs.Clear();
			foreach (GameObject pFab in fabs) {
				GameObject[] scenePrefabs = GameObject.FindGameObjectsWithTag(pFab.tag);
				foreach(GameObject scenePrefab in scenePrefabs) {
					if (scenePrefab.name == pFab.name + "(Clone)")
						AddObject(scenePrefab);
				}
			}
			ClearData();
			SavePrefabs();
		}
		//load
		if (Input.GetKeyDown(KeyCode.L)) {
			
			//clean up the scene
			foreach (GameObject pFab in fabs) {
				GameObject[] scenePrefabs = GameObject.FindGameObjectsWithTag(pFab.tag);
				foreach (GameObject scenePrefab in scenePrefabs) {
					Destroy(scenePrefab);
				}
			}
			//Bring in the saved objects
			LoadPrefabs();
		}
	}
	
	public void LoadPrefabs ()
	{
		// If our save file doesn't exist, there are no prefabs to load.
		if (!ES2.Exists (saveFile))
			return;
		
		// Load the number of prefabs we need to instantiate.
		int prefabCount = ES2.Load<int> (saveFile + "?tag=prefabCount");
      
		// For each prefab that we need to load ...
		for (int i=0; i<prefabCount; i++) {
			// Create a new instance of the prefab.
			foreach (GameObject pFab in fabs) {
				GameObject newPrefab = Instantiate (pFab) as GameObject;
           
				// Load the Transform for that particular prefab using the
				// ES2 self-assigning Load.
				ES2.Load<Transform> (saveFile + "?tag=transform" + i, newPrefab.transform);
			}
          
			// Add the GameObject to the list.
			//createdPrefabs.Add (newPrefab);
		}
	}
    
	public void SavePrefabs ()
	{
		// Save the number of prefabs we're saving.
		ES2.Save (createdPrefabs.Count, saveFile + "?tag=prefabCount");
        
		// Now save the Transform of each created prefab,
		// using the order in the list as the tag.
		for (int i=0; i < createdPrefabs.Count; i++) {
			ES2.Save (createdPrefabs [i].transform, saveFile + "?tag=transform" + createdPrefabs [i] + i);
		}
		//createdPrefabs.Clear();
	}
	
	public void ClearData () {
		ES2.Delete(saveFile);
	}
	
	public void AddObject(GameObject obj) {
		createdPrefabs.Add(obj);
	}
}
So, how can I save the transform correctly so that it loads the prefabs correctly, instead of placing all of the prefabs at every single position?
User avatar
Joel
Moodkie Staff
Posts: 4810
Joined: Wed Nov 07, 2012 10:32 pm

Re: Saving, Loading and Instantiating Prefabs

Post by Joel »

Hi whendricso,

What properties of the Transform component do you want restored which aren't currently being restored at the moment?

We don't save everything about the Transform because it's actually a very large component, so saving the entirety of it would hinder performance. However, we can add support for saving other aspects of the Transform. There are some things we cannot save; for example, transform.parent cannot be saved because this stores a reference which changes every time the application is loaded.

Regards,
Joel
WalterE
Posts: 3
Joined: Mon Jan 05, 2015 1:51 pm

Re: Saving, Loading and Instantiating Prefabs

Post by WalterE »

Hello Joel,
I want to instantiate a list of different prefab or Multiple prefabs, but the example above does not work
User avatar
Joel
Moodkie Staff
Posts: 4810
Joined: Wed Nov 07, 2012 10:32 pm

Re: Saving, Loading and Instantiating Prefabs

Post by Joel »

Hi there,

Please could you describe how the example is not working for you?

Also a quick note: since this example was written, Unity have stopped using OnApplicationQuit on mobile devices, so you should use OnApplicationPause instead of OnApplicationQuit on mobile devices. I've added a comment to the example to explain this.

You might also be better off looking at the Automatic Save Structure tutorial, as this better suits multiple prefabs and describes a method for saving instance IDs if necessary: http://www.moodkie.com/forum/viewtopic.php?f=4&t=522

All the best,
Joel
Joel @ Moodkie Interactive
Purchase Easy Save | Contact | Guides | Docs | Getting started
WalterE
Posts: 3
Joined: Mon Jan 05, 2015 1:51 pm

Re: Saving, Loading and Instantiating Prefabs

Post by WalterE »

sorry, your example work fine, the example of "whendricso" dont work
the Automatic Save Structure it's that i want
thanks
Locked