Unity List <t>序列化</t>

时间:2014-12-08 11:33:18

标签: c# list serialization save loading

尝试将List保存到PlayerPrefs。这是我尝试使用的方法......

列表是一个列表...

BaseEnemy类是......

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 [System.Serializable] 
 public class BaseEnemy: MonoBehaviour {


 private StatCalculations statCalculationsScript = new StatCalculations();
 private CalculateXP calculateXPScript = new CalculateXP();

 public bool isAlive;
 public float timeOfDeath;
 public bool isCaptured;
 public int number;
 public string enemyName;
 public string description;
 public bool isFromTrade;
 public int level;
 public int evolveLevel;
 public Types.TypesList type01;
 public Types.TypesList type02;
 public Sexes.SexesList sex;
 public Natures.NaturesList nature;
 public string ability01;
 public string ability02;
 public int baseHP;
 public int baseATK;
 public int baseDEF;
 public int baseSPATK;
 public int baseSPDEF;
 public int baseSPD;
 public int maxHP;
 public int maxATK;
 public int maxDEF;
 public int maxSPATK;
 public int maxSPDEF;
 public int maxSPD;
 public int curHP;
 public int curATK;
 public int curDEF;
 public int curSPATK;
 public int curSPDEF;
 public int curSPD;
 public float evasion;
 public float accuracy;
 public int hpEV;
 public int atkEV;
 public int defEV;
 public int spatkEV;
 public int spdefEV;
 public int spdEV;
 public int hpIV;
 public int atkIV;
 public int defIV;
 public int spatkIV;
 public int spdefIV;
 public int spdIV;
 public int baseEXPYield;
 public LevelingRates.LevelingRatesList levelingRate;
 public int currentXP;
 public int requiredXP;
 public int hpEVYield;
 public int atkEVYield;
 public int defEVYield;
 public int spatkEVYield;
 public int spdefEVYield;
 public int spdEVYield;
 public int baseFriendship;
 public int catchRate;
 public StatusConditions.StatusConditionsList statusCondition;
 public List<BaseMove> enemyMoves = new List<BaseMove>();
 public BaseItem equippedItem;
 public BaseItem EquippedItem{
     get{return equippedItem;}
     set{equippedItem = value;}
 }

 public bool IsCaptured{
     get{return isCaptured;}
     set{isCaptured = value;}
 }
 public string EnemyName{
     get{return enemyName;}
     set{enemyName = value;}
 }
 public string Description{
     get{return description;}
     set{description = value;}
 }
 public bool IsFromTrade{
     get{return isFromTrade;}
     set{isFromTrade = value;}
 }
 public int Number{
     get{return number;}
     set{number = value;}
 }
 public int Level{
     get{return level;}
     set{level = value;}
 }
 public int EvolveLevel{
     get{return evolveLevel;}
     set{evolveLevel = value;}
 }
 public Types.TypesList Type01{
     get{return type01;}
     set{type01 = value;}
 }
 public Types.TypesList Type02{
     get{return type02;}
     set{type02 = value;}
 }
 public Sexes.SexesList Sex{
     get{return sex;}
     set{sex = value;}
 }
 public Natures.NaturesList Nature{
     get{return nature;}
     set{nature = value;}
 }
 public string Ability01{
     get{return ability01;}
     set{ability01 = value;}
 }
 public string Ability02{
     get{return ability02;}
     set{ability02 = value;}
 }
 public int BaseHP{
     get{return baseHP;}
     set{baseHP = value;}
 }
 public int BaseATK{
     get{return baseATK;}
     set{baseATK = value;}
 }
 public int BaseDEF{
     get{return baseDEF;}
     set{baseDEF = value;}
 }
 public int BaseSPATK{
     get{return baseSPATK;}
     set{baseSPATK = value;}
 }
 public int BaseSPDEF{
     get{return baseSPDEF;}
     set{baseSPDEF = value;}
 }
 public int BaseSPD{
     get{return baseSPD;}
     set{baseSPD = value;}
 }
 public int CurHP{
     get{return curHP;}
     set{curHP = value;}
 }
 public int CurATK{
     get{return curATK;}
     set{curATK = value;}
 }
 public int CurDEF{
     get{return curDEF;}
     set{curDEF = value;}
 }
 public int CurSPATK{
     get{return curSPATK;}
     set{curSPATK = value;}
 }
 public int CurSPDEF{
     get{return curSPDEF;}
     set{curSPDEF = value;}
 }
 public int CurSPD{
     get{return curSPD;}
     set{curSPD = value;}
 }
 public int MaxHP{
     get{return maxHP;}
     set{maxHP = value;}
 }
 public int MaxATK{
     get{return maxATK;}
     set{maxATK = value;}
 }
 public int MaxDEF{
     get{return maxDEF;}
     set{maxDEF = value;}
 }
 public int MaxSPATK{
     get{return maxSPATK;}
     set{maxSPATK = value;}
 }
 public int MaxSPDEF{
     get{return maxSPDEF;}
     set{maxSPDEF = value;}
 }
 public int MaxSPD{
     get{return maxSPD;}
     set{maxSPD = value;}
 }
 public float Evasion{
     get{return evasion;}
     set{evasion = value;}
 }
 public float Accuracy{
     get{return accuracy;}
     set{accuracy = value;}
 }
 public int HPEV{
     get{return hpEV;}
     set{hpEV = value;}
 }
 public int ATKEV{
     get{return atkEV;}
     set{atkEV = value;}
 }
 public int DEFEV{
     get{return defEV;}
     set{defEV = value;}
 }
 public int SPATKEV{
     get{return spatkEV;}
     set{spatkEV = value;}
 }
 public int SPDEFEV{
     get{return spdefEV;}
     set{spdefEV = value;}
 }
 public int SPDEV{
     get{return spdEV;}
     set{spdEV = value;}
 }
 public int HPIV{
     get{return hpIV;}
     set{hpIV = value;}
 }
 public int ATKIV{
     get{return atkIV;}
     set{atkIV = value;}
 }
 public int DEFIV{
     get{return defIV;}
     set{defIV = value;}
 }
 public int SPATKIV{
     get{return spatkIV;}
     set{spatkIV = value;}
 }
 public int SPDEFIV{
     get{return spdefIV;}
     set{spdefIV = value;}
 }
 public int SPDIV{
     get{return spdIV;}
     set{spdIV = value;}
 }
 public int BaseEXPYield{
     get{return baseEXPYield;}
     set{baseEXPYield = value;}
 }
 public LevelingRates.LevelingRatesList LevelingRate{
     get{return levelingRate;}
     set{levelingRate = value;}
 }
 public int CurrentXP{
     get{return currentXP;}
     set{currentXP = value;}
 }
 public int RequiredXP{
     get{return requiredXP;}
     set{requiredXP = value;}
 }
 public int HPEVYield{
     get{return hpEVYield;}
     set{hpEVYield = value;}
 }
 public int ATKEVYield{
     get{return atkEVYield;}
     set{atkEVYield = value;}
 }
 public int DEFEVYield{
     get{return defEVYield;}
     set{defEVYield = value;}
 }
 public int SPATKEVYield{
     get{return spatkEVYield;}
     set{spatkEVYield = value;}
 }
 public int SPDEFEVYield{
     get{return spdefEVYield;}
     set{spdefEVYield = value;}
 }
 public int SPDEVYield{
     get{return spdEVYield;}
     set{spdEVYield = value;}
 }
 public int BaseFriendship{
     get{return baseFriendship;}
     set{baseFriendship = value;}
 }
 public int CatchRate{
     get{return catchRate;}
     set{catchRate = value;}
 }
 public StatusConditions.StatusConditionsList StatusCondition{
     get{return statusCondition;}
     set{statusCondition = value;}
 }

 void Awake(){
     isAlive = true;
     SetupEnemy();
 }

 void Start(){
 }

 void Update(){
     SetupGrowingStats();
 }

 public void SetupEnemy(){
     SetupIV();
     ChooseEnemySex();
     ChooseEnemyNature();
     SetupStats();
 }

 private void SetupIV(){
     HPIV = Random.Range(0,15);
     ATKIV = Random.Range(0,15);
     DEFIV = Random.Range(0,15);
     SPATKIV = Random.Range(0,15);
     SPDEFIV = Random.Range(0,15);
     SPDIV = Random.Range(0,15);
 }

 private void ChooseEnemySex(){
     if(ATKIV > 2){
         Sex = Sexes.SexesList.MALE;
     }else if(ATKIV <= 2){
         Sex = Sexes.SexesList.FEMALE;
     }
 }

 private void ChooseEnemyNature(){
     System.Array natures = System.Enum.GetValues (typeof(Natures.NaturesList));
     Nature = (Natures.NaturesList)natures.GetValue (Random.Range(0,24));
 }

 private void SetupStats(){
     MaxHP = statCalculationsScript.CalculateHP (BaseHP, Level, HPIV, HPEV);
     MaxATK = statCalculationsScript.CalculateStat (BaseATK, Level, ATKIV, ATKEV, Nature, StatCalculations.StatTypes.ATTACK);
     MaxDEF = statCalculationsScript.CalculateStat (BaseDEF, Level, DEFIV, DEFEV, Nature, StatCalculations.StatTypes.DEFENSE);
     MaxSPATK = statCalculationsScript.CalculateStat (BaseSPATK, Level, SPATKIV, SPATKEV, Nature, StatCalculations.StatTypes.SPECIALATTACK);
     MaxSPDEF = statCalculationsScript.CalculateStat (BaseSPDEF, Level, SPDEFIV, SPDEFEV, Nature, StatCalculations.StatTypes.SPECIALDEFENSE);
     MaxSPD = statCalculationsScript.CalculateStat (BaseSPD, Level, SPDIV, SPDEV, Nature, StatCalculations.StatTypes.SPEED);
     CurHP = MaxHP;
     CurATK = MaxATK;
     CurDEF = MaxDEF;
     CurSPATK = MaxSPATK;
     CurSPDEF = MaxSPDEF;
     CurSPD = MaxSPD;
     Evasion = 1.0f;
     Accuracy = 1.0f;
     CurrentXP = calculateXPScript.CalculateCurrentXP(Level, LevelingRate);
     RequiredXP = calculateXPScript.CalculateRequiredXP(Level, LevelingRate);
 }

 public void AdjustCurrentHP(int adj){
     CurHP += adj;
     if(CurHP < 0){
         CurHP = 0;
     }
     if(CurHP > MaxHP){
         CurHP = MaxHP;
     }
 }
 public void AdjustCurrentATK(int adj){
     CurATK += adj;
     if(CurATK < 0){
         CurATK = 0;
     }
     if(CurATK > MaxATK){
         CurATK = MaxATK;
     }
 }
 public void AdjustCurrentDEF(int adj){
     CurDEF += adj;
     if(CurDEF < 0){
         CurDEF = 0;
     }
     if(CurDEF > MaxDEF){
         CurDEF = MaxDEF;
     }
 }
 public void AdjustCurrentSPATK(int adj){
     CurSPATK += adj;
     if(CurSPATK < 0){
         CurSPATK = 0;
     }
     if(CurSPATK > MaxSPATK){
         CurSPATK = MaxSPATK;
     }
 }
 public void AdjustCurrentSPDEF(int adj){
     CurSPDEF += adj;
     if(CurSPDEF < 0){
         CurSPDEF = 0;
     }
     if(CurSPDEF > MaxSPDEF){
         CurSPDEF = MaxSPDEF;
     }
 }
 public void AdjustCurrentSPD(int adj){
     CurSPD += adj;
     if(CurSPD < 0){
         CurSPD = 0;
     }
     if(CurSPD > MaxSPD){
         CurSPD = MaxSPD;
     }
 }

 public void AdjustEXP(int adj){
     CurrentXP += adj;
     if(CurrentXP >= RequiredXP){
         Level += 1;
         RequiredXP = calculateXPScript.CalculateRequiredXP(Level, LevelingRate);
         SetupGrowingStats();
     }
 }

 private void SetupGrowingStats(){
     MaxHP = statCalculationsScript.CalculateHP (BaseHP, Level, HPIV, HPEV);
     MaxATK = statCalculationsScript.CalculateStat (BaseATK, Level, ATKIV, ATKEV, Nature, StatCalculations.StatTypes.ATTACK);
     MaxDEF = statCalculationsScript.CalculateStat (BaseDEF, Level, DEFIV, DEFEV, Nature, StatCalculations.StatTypes.DEFENSE);
     MaxSPATK = statCalculationsScript.CalculateStat (BaseSPATK, Level, SPATKIV, SPATKEV, Nature, StatCalculations.StatTypes.SPECIALATTACK);
     MaxSPDEF = statCalculationsScript.CalculateStat (BaseSPDEF, Level, SPDEFIV, SPDEFEV, Nature, StatCalculations.StatTypes.SPECIALDEFENSE);
     MaxSPD = statCalculationsScript.CalculateStat (BaseSPD, Level, SPDIV, SPDEV, Nature, StatCalculations.StatTypes.SPEED);
     CurrentXP = calculateXPScript.CalculateCurrentXP(Level, LevelingRate);
     RequiredXP = calculateXPScript.CalculateRequiredXP(Level, LevelingRate);
 }

 public void SetDead(){
     this.isAlive = false;
     this.timeOfDeath = Time.time;

     ReSpawner.deadEnemy.Add(this);

     this.gameObject.SetActive(false);
 }


}

持有List的类是EnemyRoster ......这是......

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 [System.Serializable]
 public class EnemyRoster : MonoBehaviour {


 public List<BaseEnemy> enemyRoster = new List<BaseEnemy>();

 void Start () {

 }

 void Update () {

 }

}

我必须处理保存和加载的脚本是这个......

 using UnityEngine;
 using System;
 using System.Collections;
 using System.Collections.Generic;
 using System.Runtime.Serialization.Formatters.Binary;
 using System.IO;

 public class GameMaster : MonoBehaviour {

 public Camera mainCamera;

 private GameObject playerCharacter;
 private GameObject headsUpDisplay;
 private GameObject eventSystem;
 private GameObject pc;
 private GameObject cam;
 private PlayerCharacter pcScript;
 private Vector3 playerSpawnPointPos;

 void Awake(){
     DontDestroyOnLoad(this);
 }

 void Start () {
     playerSpawnPointPos = ChooseSpawnPoint.PickSpawnPoint(Application.loadedLevelName.ToString(), PlayerPrefs.GetString("Last Zone", "Town"));
     playerCharacter = (GameObject)Resources.Load("Prefabs/Player Character Prefab");
     pc = Instantiate(playerCharacter, playerSpawnPointPos, Quaternion.identity) as GameObject;
     if(Application.loadedLevelName == "Main Menu" || Application.loadedLevelName == "Character Generation"){
         pc.GetComponent<Movement>().enabled = false;
         pc.GetComponent<BallThrow>().enabled = false;
         pc.GetComponent<Encounter>().enabled = false;
     }
     pc.name = "Player Character";
     pcScript = pc.GetComponent<PlayerCharacter>();
     cam = Instantiate(mainCamera, Vector3.zero, Quaternion.identity) as GameObject;
     if(Application.loadedLevelName != "Main Menu" || Application.loadedLevelName != "Character Generation"){
         LoadCharacterData();
         headsUpDisplay = (GameObject)Resources.Load("Prefabs/HUD Prefab");
         eventSystem = (GameObject)Resources.Load("Prefabs/Event System Prefab");
         Instantiate(headsUpDisplay, Vector3.zero, Quaternion.identity);
         Instantiate(eventSystem, Vector3.zero, Quaternion.identity);
     }
     pcScript.LastZone = Application.loadedLevelName.ToString();
     SaveCharacterData();
 }

 public static string ObjectToStr<BaseEnemy> (BaseEnemy _saveMe)
 {
     BinaryFormatter _bin = new BinaryFormatter ();
     MemoryStream _mem = new MemoryStream ();
     _bin.Serialize (_mem, _saveMe);

     return Convert.ToBase64String (_mem.GetBuffer());
 }
 public static BaseEnemy StrToObject<BaseEnemy> (string _data) where BaseEnemy : class
 {
     if (!String.IsNullOrEmpty (_data)) {
         BinaryFormatter _bin = new BinaryFormatter ();
         try {
             MemoryStream _mem = new MemoryStream (Convert.FromBase64String (_data));

             BaseEnemy _obj = _bin.Deserialize (_mem) as BaseEnemy;

             return _obj;
         } catch (Exception ex) {
             throw new Exception (ex.Message);
         }

     } else {
         throw new Exception ("_data is null or empty");
     }
 }

 public void SaveCharacterData(){
     GameObject pc = GameObject.Find("Player Character");
     PlayerCharacter pcClass = pc.GetComponent<PlayerCharacter>();
     EnemyRoster pcERoster = pc.GetComponent<EnemyRoster>();
     EnemyInventory pcEInventory = pc.GetComponent<EnemyInventory>();

     PlayerPrefs.SetString("Player Name", pcClass.PlayerName);
     PlayerPrefs.SetInt("Player Sex", (int)pcClass.PlayerSex);
     PlayerPrefs.SetInt("Player Money", pcClass.PlayerMoney);
     PlayerPrefs.SetString("Last Zone", pcClass.LastZone);
     PlayerPrefs.SetString ("EnemyRoster", ObjectToStr<List<BaseEnemy>> (pcERoster.enemyRoster));
     PlayerPrefs.SetString ("EnemyInventory", ObjectToStr<List<BaseEnemy>> (pcEInventory.enemyInventory));
 }

 public void LoadCharacterData(){
     GameObject pc = GameObject.Find("Player Character");
     PlayerCharacter pcClass = pc.GetComponent<PlayerCharacter>();
     EnemyRoster pcERoster = pc.GetComponent<EnemyRoster>();
     EnemyInventory pcEInventory = pc.GetComponent<EnemyInventory>();

     pcClass.PlayerName = PlayerPrefs.GetString("Player Name", "Name Me");
     pcClass.PlayerSex = (Sexes.SexesList)PlayerPrefs.GetInt("Player Sex", 0);
     pcClass.PlayerMoney = PlayerPrefs.GetInt("Player Money", 0);
     pcClass.LastZone = PlayerPrefs.GetString("Last Zone", "Pallet Town");
     pcERoster.enemyRoster = StrToObject<List<BaseEnemy>> (PlayerPrefs.GetString ("EnemyRoster"));
     pcEInventory.enemyInventory = StrToObject<List<BaseEnemy>> (PlayerPrefs.GetString ("EnemyInventory"));
 }

}

问题是......我收到以下错误......

  

SerializationException:在程序集中键入UnityEngine.MonoBehaviour   UnityEngine,Version = 0.0.0.0,Culture = neutral,PublicKeyToken = null   未标记为可序列化。   System.Runtime.Serialization.FormatterServices.GetSerializableMembers   (System.Type类型,StreamingContext上下文)(at   /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Runtime.Serialization/FormatterServices.cs:101)   System.Runtime.Serialization.Formatters.Binary.CodeGenerator.GenerateMetadataTypeInternal   (System.Type类型,StreamingContext上下文)(at   /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/CodeGenerator.cs:78)   System.Runtime.Serialization.Formatters.Binary.CodeGenerator.GenerateMetadataType   (System.Type类型,StreamingContext上下文)(at   /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/CodeGenerator.cs:64)   System.Runtime.Serialization.Formatters.Binary.ObjectWriter.CreateMemberTypeMetadata   (System.Type类型)(at   /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectWriter.cs:442)   System.Runtime.Serialization.Formatters.Binary.ObjectWriter.GetObjectData   (System.Object obj,   System.Runtime.Serialization.Formatters.Binary.TypeMetadata&安培;元数据,   System.Object的&安培;数据)(at   /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectWriter.cs:430)   System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteObject   (System.IO.BinaryWriter writer,Int64 id,System.Object obj)(at   /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectWriter.cs:306)   System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteObjectInstance   (System.IO.BinaryWriter writer,System.Object obj,Boolean   isValueObject)(at   /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectWriter.cs:293)   System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteQueuedObjects   (System.IO.BinaryWriter writer)(at   /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectWriter.cs:271)   System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteObjectGraph   (System.IO.BinaryWriter writer,System.Object obj,   System.Runtime.Remoting.Messaging.Header [] headers)(at   /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectWriter.cs:256)   System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize   (System.IO.Stream serializationStream,System.Object图,   System.Runtime.Remoting.Messaging.Header [] headers)(at   /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/BinaryFormatter.cs:232)   System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize   (System.IO.Stream serializationStream,System.Object图)(at   /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/BinaryFormatter.cs:211)   GameMaster.ObjectToStr [列表1] (System.Collections.Generic.List 1   _saveMe)(在Assets / Scripts / Game Master / GameMaster.cs:58)GameMaster.SaveCharacterData()(在Assets / Scripts / Game)   Master / GameMaster.cs:91)CharacterGeneratorGUI.LetsGo()(at   资产/脚本/图形用户界面/ CharacterGeneratorGUI.cs:128)   UnityEngine.Events.InvokableCall.Invoke(System.Object [] args)(at   C:/BuildAgent/work/d63dfc6385190b60/Runtime/Export/UnityEvent.cs:109)   UnityEngine.Events.InvokableCallList.Invoke(System.Object []   参数)(at   C:/BuildAgent/work/d63dfc6385190b60/Runtime/Export/UnityEvent.cs:575)   UnityEngine.Events.UnityEventBase.Invoke(System.Object []参数)   (在   C:/BuildAgent/work/d63dfc6385190b60/Runtime/Export/UnityEvent.cs:717)   UnityEngine.Events.UnityEvent.Invoke()(at   C:/BuildAgent/work/d63dfc6385190b60/Runtime/Export/UnityEvent_0.cs:53)   UnityEngine.UI.Button.Press()(at   C:/BuildAgent/work/d63dfc6385190b60/Extensions/guisystem/guisystem/UI/Core/Button.cs:35)   UnityEngine.UI.Button.OnPointerClick   (UnityEngine.EventSystems.PointerEventData eventData)(at   C:/BuildAgent/work/d63dfc6385190b60/Extensions/guisystem/guisystem/UI/Core/Button.cs:44)   UnityEngine.EventSystems.ExecuteEvents.Execute(IPointerClickHandler   handler,UnityEngine.EventSystems.BaseEventData eventData)(at   C:/BuildAgent/work/d63dfc6385190b60/Extensions/guisystem/guisystem/EventSystem/ExecuteEvents.cs:52)   UnityEngine.EventSystems.ExecuteEvents.Execute [IPointerClickHandler]   (UnityEngine.GameObject目标,UnityEngine.EventSystems.BaseEventData   eventData,UnityEngine.EventSystems.EventFunction`1仿函数)(at   C:/BuildAgent/work/d63dfc6385190b60/Extensions/guisystem/guisystem/EventSystem/ExecuteEvents.cs:269)   UnityEngine.EventSystems.EventSystem:更新()

有人可以告诉我,我做错了吗?感谢。

编辑 - 所以我添加了BaseEnemy脚本:

protected BaseEnemy(SerializationInfo info, StreamingContext context)
{
    this.isAlive = info.GetBoolean("isAlive");
    this.Number = info.GetInt32("number");
    this.EnemyName = info.GetString("enemyName");
    this.Description = info.GetString("description");
    this.IsFromTrade = info.GetBoolean("isFromTrade");
    this.Level = info.GetInt32("level");
    this.EvolveLevel = info.GetInt32("evolveLevel");
    //this.Type01 = info.GetEnumerator("type01");
    //this.Type02 = info.GetEnumerator("type02");
    //this.sex = info.GetEnumerator("sex");
    //this.Nature = info.GetEnumerator("nature");
    this.Ability01 = info.GetString("ability01");
    this.Ability02 = info.GetString("ability02");
    this.BaseHP = info.GetInt32("baseHP");
    this.BaseATK = info.GetInt32("baseATK");
    this.BaseDEF = info.GetInt32("baseDEF");
    this.BaseSPATK = info.GetInt32("baseSPATK");
    this.BaseSPDEF = info.GetInt32("baseSPDEF");
    this.BaseSPD = info.GetInt32("baseSPD");
    this.MaxHP = info.GetInt32("maxHP");
    this.MaxATK = info.GetInt32("maxATK");
    this.MaxDEF = info.GetInt32("maxDEF");
    this.MaxSPATK = info.GetInt32("maxSPATK");
    this.MaxSPDEF = info.GetInt32("maxSPDEF");
    this.MaxSPD = info.GetInt32("maxSPD");
    this.CurHP = info.GetInt32("curHP");
    this.CurATK = info.GetInt32("curATK");
    this.CurDEF = info.GetInt32("curDEF");
    this.CurSPATK = info.GetInt32("curSPATK");
    this.CurSPDEF = info.GetInt32("curSPDEF");
    this.CurSPD = info.GetInt32("curSPD");
    this.Evasion = info.GetInt32("evasion");
    this.Accuracy = info.GetInt32("accuracy");
    this.HPEV = info.GetInt32("hpEV");
    this.ATKEV = info.GetInt32("atkEV");
    this.DEFEV = info.GetInt32("defEV");
    this.SPATKEV = info.GetInt32("spatkEV");
    this.SPDEFEV = info.GetInt32("spdefEV");
    this.SPDEV = info.GetInt32("spdEV");
    this.HPIV = info.GetInt32("hpIV");
    this.ATKIV = info.GetInt32("atkIV");
    this.DEFIV = info.GetInt32("defIV");
    this.SPATKIV = info.GetInt32("spatkIV");
    this.SPDEFIV = info.GetInt32("spdefIV");
    this.SPDIV = info.GetInt32("spdIV");
    this.BaseEXPYield = info.GetInt32("baseEXPYield");
    //this.LevelingRate = info.GetEnumerator("levelingRate");
    this.CurrentXP = info.GetInt32("currentXP");
    this.RequiredXP = info.GetInt32("requiredXP");
    this.HPEVYield = info.GetInt32("hpEVYield");
    this.ATKEVYield = info.GetInt32("atkEVYield");
    this.DEFEVYield = info.GetInt32("defEVYield");
    this.SPATKEVYield = info.GetInt32("spatkEVYield");
    this.SPDEFEVYield = info.GetInt32("spdefEVYield");
    this.SPDEVYield = info.GetInt32("spdEVYield");
    this.BaseFriendship = info.GetInt32("baseFriendship");
    this.CatchRate = info.GetInt32("catchRate");
    //this.StatusCondition = info.GetEnumerator("statusCondition");
}

public void GetObjectData(SerializationInfo info, StreamingContext context)
{
    info.AddValue("isAlive", isAlive);
    info.AddValue("number", number);
    info.AddValue("enemyName", enemyName);
    info.AddValue("description", description);
    info.AddValue("isFromTrade", isFromTrade);
    info.AddValue("level", level);
    info.AddValue("evolveLevel", evolveLevel);
    //info.AddValue("type01", type01);
    //info.AddValue("type02", type02);
    //info.AddValue("sex", sex);
    //info.AddValue("nature", nature);
    info.AddValue("ability01", ability01);
    info.AddValue("ability02", ability02);
    info.AddValue("baseHP", baseHP);
    info.AddValue("baseATK", baseATK);
    info.AddValue("baseDEF", baseDEF);
    info.AddValue("baseSPATK", baseSPATK);
    info.AddValue("baseSPDEF", baseSPDEF);
    info.AddValue("baseSPD", baseSPD);
    info.AddValue("maxHP", maxHP);
    info.AddValue("maxATK", maxATK);
    info.AddValue("maxDEF", maxDEF);
    info.AddValue("maxSPATK", maxSPATK);
    info.AddValue("maxSPDEF", maxSPDEF);
    info.AddValue("maxSPD", maxSPD);
    info.AddValue("curHP", curHP);
    info.AddValue("curATK", curATK);
    info.AddValue("curDEF", curDEF);
    info.AddValue("curSPATK", curSPATK);
    info.AddValue("curSPDEF", curSPDEF);
    info.AddValue("curSPD", curSPD);
    info.AddValue("evasion", evasion);
    info.AddValue("accuracy", accuracy);
    info.AddValue("hpEV", hpEV);
    info.AddValue("atkEV", atkEV);
    info.AddValue("defEV", defEV);
    info.AddValue("spatkEV", spatkEV);
    info.AddValue("spdefEV", spdefEV);
    info.AddValue("spdEV", spdEV);
    info.AddValue("hpIV", hpIV);
    info.AddValue("atkIV", atkIV);
    info.AddValue("defIV", defIV);
    info.AddValue("spatkIV", spatkIV);
    info.AddValue("spdefIV", spdefIV);
    info.AddValue("spdIV", spdIV);
    info.AddValue("baseEXPYield", baseEXPYield);
    info.AddValue("levelingRate", levelingRate);
    info.AddValue("currentXP", currentXP);
    info.AddValue("requiredXP", requiredXP);
    info.AddValue("hpEVYield", hpEVYield);
    info.AddValue("atkEVYield", atkEVYield);
    info.AddValue("defEVYield", defEVYield);
    info.AddValue("spatkEVYield", spatkEVYield);
    info.AddValue("spdefEVYield", spdefEVYield);
    info.AddValue("spdEVYield", spdEVYield);
    info.AddValue("baseFriendship", baseFriendship);
    info.AddValue("catchRate", catchRate);
    info.AddValue("statusCondition", statusCondition);
}

在GameMaster脚本中(处理保存和加载):

    private void SaveEnemyRoster(string path, object obj){
    using (TextWriter writer = new StreamWriter(path)){
        XmlSerializer xml = new XmlSerializer(typeof(List<BaseEnemy>));
        xml.Serialize(writer, obj);
    }
}
private List<BaseEnemy> LoadEnemyRoster(string path){
    List<BaseEnemy> tempRoster = new List<BaseEnemy>();
    using (TextReader reader = new StreamReader(path)){
        XmlSerializer xml = new XmlSerializer(typeof(List<BaseEnemy>));
        tempRoster = (List<BaseEnemy>)xml.Deserialize(reader);
    }
    return tempRoster;
}

2 个答案:

答案 0 :(得分:0)

您的课程应该实现ISerializable 序列化构造函数,以及方法GetObjectData()。实现将如下所示;

public class BaseEnemy: MonoBehaviour, ISerializable 
{
    //...

    protected BaseEnemey(SerializationInfo info, StreamingContext context)
    {
        //map all your properties here
        this.isAlive = info.GetBoolean("isAlive");
        //...
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("isAlive", isAlive);
        //...
    }
}

祝你好运,你似乎有一个很多的属性。 This也可以帮助你。

题外话;出于好奇,你在创造一个口袋妖怪游戏吗?

答案 1 :(得分:0)

在序列化期间,BinarySerializer会尝试完全(并自动)序列化您的对象,但由于这个原因而失败:基类MonoBehavior不可序列化。

为了达到你想要的效果,我建议为你的类实现ISerializable接口,这样你就可以更好地控制序列化对象的方式。

以下是通过此方法序列化对象的简单示例:ISerializable example

相关问题