我可以在保存选项文件中序列化Vector3

时间:2016-04-10 03:45:27

标签: c# serialization unity3d

我正在为游戏保存和加载选项,我正在尝试序列化Vector3但是我收到了这个错误:

SerializationException: Type UnityEngine.Vector3 is not marked as Serializable.

当我查看文档时,我在Serializable类型列表中看到了Vector3:

Serializable types are:
- Some built-in types like Vector2, Vector3, Vector4, Quaternion, Matrix4x4, Color, Rect, LayerMask.

我的代码是:

public Options_Settings GameOptions { get; private set; }

public void SaveOptionSettings(){
    // Create the Binary Formatter.
    BinaryFormatter bf = new BinaryFormatter();
    // Stream the file with a File Stream. (Note that File.Create() 'Creates' or 'Overwrites' a file.)
    FileStream file = File.Create(Application.persistentDataPath + "/OptionsInfo.dat");
    // Serialize the file so the contents cannot be manipulated.
    bf.Serialize(file, GameOptions);  // <---- Error is here
    // Close the file to prevent any corruptions
    file.Close();
}

我的Options_Settings:

using UnityEngine;
using System;

[Serializable]
public class Options_Settings {

public bool MusicToggle { get; set; }
public float MusicVolume { get; set; }

public bool SFXToggle { get; set; }
public float SFXVolume { get; set; }

public Vector3 UIOneScaling { get; set; }
public Vector3 UITwoScaling { get; set; }
public Vector3 UIThreeScaling { get; set; }


public void Default () {

    MusicToggle = true;
    MusicVolume = 0.5f;

    SFXToggle = true;
    SFXVolume = 0.5f;

    UIOneScaling = Vector3.one;
    UITwoScaling = Vector3.one;
    UIThreeScaling = Vector3.one;
}

}

我知道我可以做一个解决方法,只为每个向量制作3个浮点数并以这种方式传递它们但我想知道我做错了什么,因为文档说我可以做Vector3,这会阻止额外的编码和做单调作用

1 个答案:

答案 0 :(得分:1)

虽然unity CAN确实可以序列化Vector3变量,但它不能将ACCESSOR序列化为Vector3。

我在你的代码中看到了这个访问者:

public Vector3 UIOneScaling { get; set; }

但是我没有看到存储的ACTUAL向量变量:访问者只是一个函数。

我原本希望看到类似的东西:

[SerializeField]  // needed to serialize private fields
private Vector3 _UIOneScaling; //a member variable to hold the data
public Vector3 UIOneScaling {
    get return {_UIOneScaling;} 
    set {_UIOneScaling=value;} 
}

在这种情况下,成员 VARIABLE _UIOneScaling将被序列化。