Question by
Jeswer · Feb 08, 2016 at 10:31 AM ·
c#playerprefsscene-loadinginitialization
Problem with instantiating objects using playerprefs when switching scenes
So I'm calling this function in the main menu in the onClick of my Button. Attempting to switch to a new scene and then instantiate objects in there, but the objects seem to get instantiated in the main menu scene and not the Saves scene. Why is this happening? and how can I make the objects get instantiated in the Saves scene?
public void ToSavedFiles() { //Switch scenes, to the saved files. SceneManager.LoadScene("Saves");
//Generate buttons for the savedFiles, with which the play can load a unique saved file.
int amountOfsaves = PlayerPrefs.GetInt("SavedFilesCount");
GameObject prefabTest = (GameObject)Resources.Load("Saved");
GameObject savedTest = Instantiate(prefabTest);
float SavedWidth = savedTest.GetComponent<RectTransform>().rect.width;
float savesPerRow = (Screen.width / SavedWidth + SavedWidth * 0.5f) / 1.5f;
for (int i = 0; i < amountOfsaves; i++)
{
GameObject prefab = (GameObject)Resources.Load("Saved");
GameObject saved = Instantiate(prefab);
Transform t = saved.transform;
string namE = "Save" + i;
saved.name = namE;
t.transform.name = namE;
float xPos = i * SavedWidth;
float yPos = 0;
t.transform.position = new Vector3(xPos, yPos, 0);
t.SetParent(GameObject.Find("Canvas").transform, true);
t.localRotation = Quaternion.identity;
}
}
Comment
Found a solution: Instantiate the objects in the new scene, by adding a script to one of the objects in the new scene. In the awake/start function of the new scene you instantiate the objects. Now they will appear :D.