简体   繁体   中英

Cannot cast from source type to destination type when deserialize a file

I am struggling with save/read file from two separate scripts, first time testing trying to save/read files, outside of playerPrefs, in Unity. I am saving the file in one scene and tries to open the file in another scene. Obviously there is a cast problem but i cannot figure out what the problem is.

Here is the code that creates the file:

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

public class SubmitScript : MainScript {

[Serializable]
public class CardEntry {
    public int card_nr;
    public bool card_backFaceUp;
    public float card_posX;
    public float card_posY;
    public float card_posZ;
    public float card_rotZ;
}

public List<CardEntry> cardsList = new List<CardEntry>();
private GameObject cards_gameObject;


public void ReturnToSetupTemplatePanel () {

    // Set playerPref so the GameBoard is back to normal
    PlayerPrefs.SetString ("GameBoard Type","DoNormal");
    // Set playerPrefs so the Template panel is out
    PlayerPrefs.SetString ("PanelPosition", "TemplatePanel Visable");
    // Set info that there is an updated template file
    PlayerPrefs.SetString ("TemplateFile", "Exists");

    // Process the save operation
    CardEntry _cardEntry = new CardEntry ();
    _cardEntry.card_nr = 0;

    // Save all card objects properties
    foreach (GameObject aGO in master_GameObject_List) {

        cards_gameObject = GameObject.FindWithTag(aGO.tag);

        // Add the cards properties
        _cardEntry.card_nr++;
        if (cards_gameObject.tag.LastIndexOf ("B") != -1) { // Card have back face up
            _cardEntry.card_backFaceUp = false;
        }
        else {
            _cardEntry.card_backFaceUp = true;
        }
        _cardEntry.card_posX = aGO.transform.position.x;
        _cardEntry.card_posY = aGO.transform.position.y;
        _cardEntry.card_posZ = aGO.transform.position.z;
        _cardEntry.card_rotZ = aGO.transform.rotation.z;
        cardsList.Add(_cardEntry);
        print ("%: " + _cardEntry.card_nr + " % " + aGO.tag);
    }

    // Save card object data
    // Get binary formatter
    var b = new BinaryFormatter ();
    // Create a file
    var f = File.Create (Application.persistentDataPath + "/tempInfo.dat");
    // Save the scores
    b.Serialize (f, cardsList);
    f.Close ();

    // Go back to SetupScene
    Application.LoadLevel("SetupScene");
}
}

Here is the code i use to open the file and try to process the output:

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


public class StartupScript : MonoBehaviour {

[Serializable]
public class CardEntry {
    public int card_nr;
    public bool card_backFaceUp;
    public float card_posX;
    public float card_posY;
    public float card_posZ;
    public float card_rotZ;
}

public List<CardEntry> cardsList2 = new List<CardEntry>();

private bool shouldPanelBeOut = false;
private string panelStatus;
public GameObject thePanel;
private string fileStatus;

public GameObject cards_gameObject;



void Start() {
    print ("Startup Script");
    // If needed
    //File.Delete (Application.persistentDataPath + "/tempInfo.dat");

    CardEntry _cardEntry = new CardEntry ();

    // Find out if the panel should be visable or not
    panelStatus = PlayerPrefs.GetString ("PanelPosition");// "TemplatePanel Visable"

    fileStatus = PlayerPrefs.GetString ("TemplateFile");

    if (panelStatus == "TemplatePanel Visable") {

        thePanel.GetComponent<RectTransform>().localPosition = new Vector3(0.0f, 0.0f, 0.0f);

        if (fileStatus == "Exists") {
            // If not blank then load it
            if (File.Exists (Application.persistentDataPath + "/tempInfo.dat")) {

                print ("File Exist");
                // Binary formatter for loading back
                var b = new BinaryFormatter();
                // Get the file
                var f = File.Open(Application.persistentDataPath + "/tempInfo.dat", FileMode.Open);
                // Load back the scores
                cardsList2 = (List<CardEntry>)b.Deserialize(f); //<<< CAST ERROR HERE
                f.Close();

            }
        }
        else {
            print("File does not Exist");
        }
    }

    print ("cardsList2.Count: " + cardsList2.Count);

}
}

The casting error is on this line:

cardsList2 = (List<CardEntry>)b.Deserialize(f); //<<< CAST ERROR HERE

...also File Exist

I have been testing for hours but cannot figure out what the problem is.

I faced with same problem and I solve it by a simple way.

cardsList2 = b.Deserialize(f) as List<CardEntry>;

I think, this will solve your problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM