- Home /
how to instantiate saved objects back into game
hi! I'm currently saving my prefabs into Assets/Resources/nameofprefab and I would like to load and instantiate them back into the game (I'm trying to make a very basic prefab load/save solution) I have been told to use Resources.Load, however, I have not been able to make it work - can anyone give me any advice on this problem?
thanks!
Answer by MHernandezOlmo · Aug 31, 2020 at 01:41 PM
Hi @Goubermouche, let's see if this helps you. Two easy ways for this:
1.-You can easily have a reference to your prefab on any script with a GameObject variable public, then drag the prefab to that script in the inspector and then instantiate itwith something like this:
public GameObject targetPrefab;
void Start()
{
Instantiate (targetPrefab);
}
2.-If you want to load them into a variable and then instantiate, just do something like this: Imagine your prefabs is under "Resources" folder, then under a folder called "Prefabs" and you called it "MyPrefab". To load it into a variable, you can just do:
GameObject targetPrefab = Resources.Load<GameObject>("Prefabs/MyPrefab");
And then do the instantiate think like above.
Hope this helps.
hi! first of all - thanks for replying! second of all - I have tried the proposed solution however I was not able to make it work - it doesn't give me an error but it leaves the game object variable empty - any idea of what I'm doing wrong?
// Start is called before the first frame update
void Start()
{
//load objects
GameObject gmb = Resources.Load<GameObject>(dataPath + "1");
}
// Update is called once per frame
void Update()
{
if (Input.Get$$anonymous$$ouseButtonDown(0))
{
Vector3 mousePos = Input.mousePosition;
mousePos.z = 2.0f;
Vector3 objectPos = Camera.main.ScreenToWorldPoint(mousePos);
var newObject = Instantiate(obj, objectPos, Quaternion.identity);
newObject.name = index.ToString();
index++;
newObject.transform.parent = transform;
objectsToSave.Add(newObject);
}
//clear save file
if (Input.GetKeyDown(KeyCode.Delete))
{
Directory.Delete(dataPath, true);
Directory.CreateDirectory(dataPath);
}
}
private void OnDestroy()
{
//save objects into the save file
if(objectsToSave.Count > 0)
{
for (int i = 0; i < objectsToSave.Count; i++)
{
string localPath = "Assets/Resources/" + objectsToSave[i].name + ".prefab";
PrefabUtility.SaveAsPrefabAsset(objectsToSave[i], localPath);
}
}
}
}
$$anonymous$$aybe your path is wrong - the docs say that in that case it does not raise an error, but just returns null: "If an asset can be found at path, it is returned with type T, otherwise returns null" in https://docs.unity3d.com/ScriptReference/Resources.Load.html
im dont think that is the issue since Im using datapath
Loading:
object gmb = Resources.Load("Assets/Resources/SaveFile/1.prefab"); Debug.Log(gmb);
I'm now getting a null value but i have no idea what I'm doing wrong
.![alt text][1] [1]: /storage/temp/166708-poznamka-2020-09-01-200748.jpg