gpt4 book ai didi

c# - Unity3d - C# - 如何备份数组的值?

转载 作者:行者123 更新时间:2023-11-30 21:39:34 25 4
gpt4 key购买 nike

我在脚本 (C#) 中定义了一个包含 67 个元素的数组。每个元素都是我定义的包含一些变量的类的对象。像下面这样:

// the Definition of the array
public Pack[] packsInfo;

// the class
[Serializable]
public class Pack
{
public int number;
public int angle;
public float zPosition;
public float beatCaseDistance;
public float gunDistance;
}

然后,我在 Inspector 中分​​配所有值。像下面这样:

enter image description here

所以...如果我突然更改任何值或什至更糟(这些值由于任何原因而消失。例如更改类参数或任何其他内容),那么我必须花费数小时来设置所有值。所以我想打印文本或文件中的所有值并保存它们。以便稍后恢复它们。我想要一个备份解决方案。我想用编程来做。 (我不想手动编写它们;)。这是浪费时间。 )

最佳答案

要保存您的数组,您可以使用例如 JsonUtillity .

很简单!祝你好运!

 void Start () {
/////////////////////// save to json
JSONObject jsonSave = new JSONObject();
for(int i=0; i < packsInfo.Length; i++) {
JSONObject packJson = new JSONObject();
packJson.AddField("number", packsInfo[i].number);
packJson.AddField("angle", packsInfo[i].angle);
packJson.AddField("z_position", packsInfo[i].zPosition);
packJson.AddField("beat_case_distance", packsInfo[i].beatCaseDistance);
packJson.AddField("gun_distance", packsInfo[i].gunDistance);
jsonSave.Add(packJson);
}

System.IO.StreamWriter streamWritter = new System.IO.StreamWriter(@"C:\MyGameFiles\packs.json");
streamWritter.WriteLine(jsonSave.Print(true));
streamWritter.Close();
streamWritter = null;
/////////////////////// read json
System.IO.StreamReader reader = new System.IO.StreamReader(@"C:\MyGameFiles\packs.json");
string jsonString = reader.ReadToEnd();
reader.Close();
reader = null;

JSONObject jsonRead = new JSONObject(jsonString);
packsInfo = new Pack[jsonRead.Count];
for(int i =0; i < jsonRead.Count; i ++) {
Pack pack = new Pack();
pack.number = (int)jsonRead[i]["number"].i;
pack.angle = (int)jsonRead[i]["angle"].i;
pack.zPosition = jsonRead[i]["z_position"].f;
pack.beatCaseDistance =jsonRead[i]["beat_case_distance"].f;
pack.gunDistance = jsonRead[i]["gun_distance"].f;
packsInfo[i] = pack;
}
}

关于c# - Unity3d - C# - 如何备份数组的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45159836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com