Question by
upariver · Nov 16, 2016 at 05:01 PM ·
saveloadfor looppersistentdatapath
for loop function causing game to not save
I am trying to save my game and it all works fine, until I get to using a for loop to obtain variables. It works fine without the for loop, however I need it to obtain the values to spawn the prefabs again.
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Collections.Generic;
using UnityEngine.UI;
public class SaveLoadManager: MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public static void SavePlayer(UI_Holder player) {
BinaryFormatter bf = new BinaryFormatter();
FileStream stream = new FileStream(Application.persistentDataPath + "/player.sav", FileMode.Create);
PlayerData data = new PlayerData(player);
bf.Serialize(stream, data);
stream.Close();
}
public static void LoadPlayer(UI_Holder main)
{
if (File.Exists(Application.persistentDataPath + "/player.sav"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream stream = new FileStream(Application.persistentDataPath + "/player.sav", FileMode.Open);
PlayerData data = bf.Deserialize(stream) as PlayerData;
main.isSetupComplete = data.SetupComplete;
main.SlotNumber = data.SlotNumber;
main.Username = data.Username;
main.SpawnChildrenScroll(data.ChildNumber);
//main.Children = data.Children;
stream.Close();
}else
{
Debug.LogError("File does not exist.");
//return new int[1];
}
}
}
[Serializable]
public class PlayerData
{
public int SlotNumber;
public bool SetupComplete;
public string Username;
public int ChildNumber;
public int[] ChildrenPoints;
public string[] ChildNames;
public int[] ChildID;
public PlayerData(UI_Holder player)
{
//Here you add the vars to save
SetupComplete = player.isSetupComplete;
SlotNumber = player.SlotNumber;
Username = player.Username;
ChildNumber = player.Children.Count;
// FOR LOOP GUILTY OF CHARGE
/*for( int i=0; i < ChildNumber; i++)
{
ChildrenPoints[i] = player.Children[i].GetComponent<ChildScrollContainer>().ChildPoints;
ChildNames[i] = player.Children[i].GetComponent<ChildScrollContainer>().ChildName;
}*/
//Children = player.Children;
}
}
Comment
Answer by JeffHardddyyy · Nov 16, 2016 at 05:08 PM
Add "break;" to the end.
When "break" is added, it stops the for loop after it is played. Or if under certain circumstances such as "if"
It doesn't work I'm afraid. Thanks for the suggestion nonetheless.
Your answer
![](https://koobas.hobune.stream/wayback/20220612100815im_/https://answers.unity.com/themes/thub/images/avi.jpg)