简体   繁体   English

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

[英]Unity3d - C# - How can I back up of values of an array?

I Defined an array of 67 elements in a script (C#). 我在脚本(C#)中定义了67个元素的数组。 Each element is an object of a class that I defined that includes some variables. 每个元素都是我定义的包含一些变量的类的对象。 Like Below: 如下所示:

// 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;
}

Then, I Assign all the values in Inspector. 然后,我在Inspector中分配所有值。 like Below: 如下所示:

在此处输入图片说明

So ... if i suddenly change any of the values or even worse, ( the values gone for a any reason. like changing the class parameters or any thing ) then I must spend hours on setting up all the values. 所以...如果我突然更改了任何值甚至更糟((由于某种原因这些值消失了,例如更改类参数或任何东西),那么我必须花几个小时来设置所有值。 So i want to print all the values in a text, or a file and save them. 所以我想将所有值打印在文本或文件中并保存。 for recovering them later. 以便稍后恢复它们。 i want a backup solution.I want to do it whit Programming. 我想要一个备份解决方案。我想用编程来做。 ( I don't want to write them manually ;) .It is waste of time. (我不想手动编写它们;)。这是浪费时间。 )

You can achieve this by creating an editor script that gets all the values in your array and saves them to specified file via IO. 您可以通过创建一个编辑器脚本来实现此目的,该脚本将获取数组中的所有值并将其通过IO保存到指定文件中。 From there you can easily make a load function with file reading. 从那里,您可以轻松地进行读取文件的加载功能。

Here's some links to get you started: 以下是一些可帮助您入门的链接:

Unity editor scripts Unity编辑器脚本

Unity read write file Unity读写文件

To save yor array you can use for example JsonUtillity . 要保存数组,可以使用例如JsonUtillity

It is simple! 很简单! Good Luck! 祝好运!

 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;
    }
}

I know that this has been answered many times but I would recommend you use the Newtonsoft Json Library . 我知道已经回答了很多次,但是我建议您使用Newtonsoft Json Library It automates the serialisation and deserialisation of objects for you so as you change the object the json will adapt without having to make specific changes. 它为您自动实现对象的序列化和反序列化,因此当您更改对象时,json将适应,而无需进行特定更改。

To Serialise you simply do this: 要序列化,您只需执行以下操作:

string json = JsonConvert.Serialise(packsInfo); //convert to text
File.WriteAllText(path, json); //Save to disk

To deserialise you simply do this: 要反序列化,只需执行以下操作:

string json = File.ReadAllLines(path); //load the file
packsInfo = JsonConvert.DeserializeObject<Pack[]>(json); //convert to an object

That's all you have to do to save and load your data. 这就是保存和加载数据所需要做的全部工作。 To get the Library you can use NuGet to add the library to the project. 要获取库,您可以使用NuGet将库添加到项目中。 in Visual Studio Go to Tools -> NuGet package Manager -> Manage NuGet Packages for Solution then go to the browse tab and search for it. 在Visual Studio中,转到工具-> NuGet程序包管理器->管理解决方案的NuGet程序包,然后转到浏览选项卡并进行搜索。

If you have no particular reason to have the variables serialized in the editor (public) I'd advise the following steps to remove them as public: 如果您没有特殊理由要在编辑器中对变量进行序列化(公共),建议您按照以下步骤将其作为公共变量删除:

  1. Use JsonUtility and serialize your class to json when you've set all values and print it. 设置所有值并打印后,使用JsonUtility并将您的类序列化为json。

.

var json = JsonUtility.ToJson(packsInfo);
Debug.Log(json);
  1. Now, when you start your game the class will be displayed in your console, you can then copy that json and save it in a text file, for example "MyFile.txt" 现在,当您开始游戏时,该类将显示在控制台中,然后您可以复制该json并将其保存在文本文件中,例如“ MyFile.txt”

  2. Add that text file to the project and load it to your game with any of the following methods: 将该文本文件添加到项目中,然后使用以下任何一种方法将其加载到游戏中:

    • Make a public field for it and drag the file to that field: 为此设置一个公共字段并将文件拖到该字段:

      public TextAsset packInfoAsset; 公共TextAsset packInfoAsset;

    • Add it to a folder called Resources and then use the following code to get the file: 将其添加到名为Resources的文件夹中,然后使用以下代码获取文件:

      var packInfoAsset = Resources.Load("MyFile"); var packInfoAsset = Resources.Load(“ MyFile”); // Note that there is no file-ending (.txt) //请注意,没有文件结尾(.txt)

  3. And finally, deserializing the json to your previous object, so when you load the class, in your Start-method or so, you do: 最后,将json反序列化为先前的对象,这样,当您在Start方法中加载类时,您可以执行以下操作:

    packsInfo = JsonUtility.FromJson<Pack>(packInfoAsset);

And there you go, you've loaded data from a file instead of having it in the editor. 然后,您就从文件中加载了数据,而不是将其保存在编辑器中。

You can save the data to ScriptableObject which can be stored as asset. 您可以将数据保存到可以存储为资产的ScriptableObject中。

Firstly, wrap your array with a ScriptableObject class: 首先,用ScriptableObject类包装数组:

using UnityEngine;
using System.Collections;

public class PacksInfo: ScriptableObject
{
    public Pack[] packs;
}

And then create an editor script to generate the ScriptableObject from Unity editor menu. 然后创建一个编辑器脚本以从Unity编辑器菜单生成ScriptableObject。

using UnityEngine;
using System.Collections;
using UnityEditor;

public class CreatePacksInfo
{
    [MenuItem("Assets/Create/Packs Info")]
    public static PacksInfo Create()
    {
        TextAsset json = (TextAsset) 
        AssetDatabase.LoadAssetAtPath("Assets/RawData/PacksInfo.json", 
        typeof(TextAsset));
        PacksInfo asset = ScriptableObject.CreateInstance<PacksInfo>();
        JsonUtility.FromJsonOverwrite(json.text, asset);

        AssetDatabase.CreateAsset(asset, "Assets/Data/PacksInfo.asset");
        AssetDatabase.SaveAssets();
        return asset;
    }
}

In this case, I create the asset based on a json file. 在这种情况下,我将基于json文件创建资产。 If you like fill them manually in Unity Editor, you can also assign your array to the PackInfo object. 如果您希望在Unity编辑器中手动填充它们,则还可以将数组分配给PackInfo对象。

When you want to use the data, you can just declare a PackInfo variable: 当您想使用数据时,可以声明一个PackInfo变量:

public class something: MonoBehaviour
{
    public PacksInfo packsInfo;
}

And then drag the ScriptableObject asset you generated directly from Unity editor to the variable in inspector. 然后将您直接从Unity编辑器生成的ScriptableObject资产拖动到检查器中的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Unity3D中使用LitJson编辑c#中的JSON值? - How do I edit JSON values in c# with LitJson in Unity3D? 无法在Unity3D内部的C#编码脚本中实例化byte []数组; 我该如何解决? - Cannot Instantiate byte[] array in C# coding scripts inside Unity3D; How do I fix that? 我如何通过unity3d中的C#脚本关联不同的网格? - How can i relate different meshes through c# script in unity3d? 在Unity3D上的C#中释放按钮后,如何保持播放器方向? - How can I retain player orientation after a button is released in C# on Unity3D? 如何使用Unity3D检测移动设备上的抖动? C# - How can I detect a shake motion on a mobile device using Unity3D? C# 如何在 Unity3d 中将 C# 组件从一个游戏对象传递到另一个游戏对象 - how can I pass a C# component from one gameobject to another in Unity3d 如何使用模型动态生成模型的纹理图像。 (Unity3D / C#)? - How can I use a model to generate a Texture image of the model dynamically. (Unity3D/C#)? 如何在C#程序中运行“无头”(无GUI)Unity3D游戏? - How can I run a “headless” (no GUI) Unity3D game inside a C# program? 如何在 unity3D、C#、手机游戏中保存和加载关卡? - How I can save and load level in unity3D, C# , Mobile Game? C# 如何在不产生任何垃圾的情况下对列表进行排序(Unity3d) - C# How Can I Sort A List without Generating Any Garbage at All (Unity3d)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM