Saving, Loading and Instantiating Prefabs
Posted: Sun Apr 21, 2013 10:25 am
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:
In this example, we create a script which saves and loads prefabs.
The main functions we use in this example are:
- Unity's Instantiate Function to create our prefabs
- ES2.Save
- ES2.Load self-assigning function, which loads the data into the Component supplied as a second parameter.
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);
}
}