Search Unity

InvalidCastException: Specified cast is not valid. (wrapper castclass) System.Object

Discussion in 'Scripting' started by subswithjust1video, Aug 1, 2021.

Thread Status:
Not open for further replies.
  1. subswithjust1video

    subswithjust1video

    Joined:
    Jun 30, 2021
    Posts:
    2
    InvalidCastException: Specified cast is not valid.
    (wrapper castclass) System.Object.__castclass_with_cache(object,intptr,intptr)
    I recently got this error quite some times and it gets me angry I would appriciate if anyone can find the problem in the code I got this code from a tutorial I tried in yt its not my code so dont say anything about tags or that the code is messy please, thanks

    Here is the code where all the error came from :
    using UnityEngine;
    using System.IO;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;

    /// <summary>
    /// BinarySerializer is tool to save your game data in files as binary
    /// so that no body can read it or modify it,
    /// this tool is generic.
    ///
    /// Allowed types : int, float , strings, ...(all .Net types)
    /// But for unity types it accepts only 5 types: Vector2, Vector3, Vector4, Color, Quaternion.
    ///
    /// Developed by Hamza Herbou
    /// GITHUB : https://github.com/herbou
    /// </summary>

    public class BinarySerializer
    {
    static string folderName = "GameData";

    static string persistentDataPath = Application.persistentDataPath;
    static SurrogateSelector surrogateSelector = GetSurrogateSelector();

    /// <summary>
    /// Save data to disk.
    /// </summary>
    /// <param name="data">your dataClass instance.</param>
    /// <param name="filename">the file where you want to save data.</param>
    /// <returns></returns>
    public static void Save<T>(T data, string filename)
    {
    if (IsSerializable<T>())
    {
    if (!Directory.Exists(GetDirectoryPath()))
    Directory.CreateDirectory(GetDirectoryPath());

    BinaryFormatter formatter = new BinaryFormatter();

    formatter.SurrogateSelector = surrogateSelector;

    FileStream file = File.Create(GetFilePath(filename));

    formatter.Serialize(file, data);

    file.Close();
    }
    }

    /// <summary>
    /// Save data to disk.
    /// </summary>
    /// <param name="filename">the file where you saved data.</param>
    /// <returns></returns>
    public static T Load<T>(string filename)
    {
    T data = System.Activator.CreateInstance<T>();

    if (IsSerializable<T>())
    {
    if (HasSaved(filename))
    {

    BinaryFormatter formatter = new BinaryFormatter();

    formatter.SurrogateSelector = surrogateSelector;

    FileStream file = File.Open(GetFilePath(filename), FileMode.Open);

    data = (T)formatter.Deserialize(file);

    file.Close();
    }
    }

    return data;
    }

    static bool IsSerializable<T>()
    {
    bool isSerializable = typeof(T).IsSerializable;
    if (!isSerializable)
    {
    string type = typeof(T).ToString();
    Debug.LogError(
    "Class <b><color=white>" + type + "</color></b> is not marked as Serializable, "
    + "make sure to add <b><color=white>[System.Serializable]</color></b> at the top of your " + type + " class."
    );
    }

    return isSerializable;
    }


    /// <summary>
    /// Check if data is saved.
    /// </summary>
    /// <param name="filename">the file where you saved data</param>
    /// <returns></returns>
    public static bool HasSaved(string filename)
    {
    return File.Exists(GetFilePath(filename));
    }

    static string GetDirectoryPath()
    {
    return persistentDataPath + "/" + folderName;
    }

    static string GetFilePath(string filename)
    {
    return GetDirectoryPath() + "/" + filename;
    }


    //Other non-serialized types /// SS: Serialization Surrogate
    //Vector2 , Vector3 , Vector4 , Color , Quaternion.

    static SurrogateSelector GetSurrogateSelector()
    {
    SurrogateSelector surrogateSelector = new SurrogateSelector();

    Vector2_SS v2_ss = new Vector2_SS();
    Vector3_SS v3_ss = new Vector3_SS();
    Vector4_SS v4_ss = new Vector4_SS();
    Color_SS co_ss = new Color_SS();
    Quaternion_SS qu_ss = new Quaternion_SS();

    surrogateSelector.AddSurrogate(typeof(Vector2), new StreamingContext(StreamingContextStates.All), v2_ss);
    surrogateSelector.AddSurrogate(typeof(Vector3), new StreamingContext(StreamingContextStates.All), v3_ss);
    surrogateSelector.AddSurrogate(typeof(Vector4), new StreamingContext(StreamingContextStates.All), v4_ss);
    surrogateSelector.AddSurrogate(typeof(Color), new StreamingContext(StreamingContextStates.All), co_ss);
    surrogateSelector.AddSurrogate(typeof(Quaternion), new StreamingContext(StreamingContextStates.All), qu_ss);

    return surrogateSelector;
    }

    class Vector2_SS : ISerializationSurrogate
    {
    //Serialize Vector2
    public void GetObjectData(System.Object obj, SerializationInfo info, StreamingContext context)
    {
    Vector2 v2 = (Vector2)obj;
    info.AddValue("x", v2.x);
    info.AddValue("y", v2.y);
    }
    //Deserialize Vector2
    public System.Object SetObjectData(System.Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
    {
    Vector2 v2 = (Vector2)obj;

    v2.x = (float)info.GetValue("x", typeof(float));
    v2.y = (float)info.GetValue("y", typeof(float));

    obj = v2;
    return obj;
    }
    }

    class Vector3_SS : ISerializationSurrogate
    {
    //Serialize Vector3
    public void GetObjectData(System.Object obj, SerializationInfo info, StreamingContext context)
    {
    Vector3 v3 = (Vector3)obj;
    info.AddValue("x", v3.x);
    info.AddValue("y", v3.y);
    info.AddValue("z", v3.z);
    }
    //Deserialize Vector3
    public System.Object SetObjectData(System.Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
    {
    Vector3 v3 = (Vector3)obj;

    v3.x = (float)info.GetValue("x", typeof(float));
    v3.y = (float)info.GetValue("y", typeof(float));
    v3.z = (float)info.GetValue("z", typeof(float));

    obj = v3;
    return obj;
    }
    }

    class Vector4_SS : ISerializationSurrogate
    {
    //Serialize Vector4
    public void GetObjectData(System.Object obj, SerializationInfo info, StreamingContext context)
    {
    Vector4 v4 = (Vector4)obj;
    info.AddValue("x", v4.x);
    info.AddValue("y", v4.y);
    info.AddValue("z", v4.z);
    info.AddValue("w", v4.w);
    }
    //Deserialize Vector4
    public System.Object SetObjectData(System.Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
    {
    Vector4 v4 = (Vector4)obj;

    v4.x = (float)info.GetValue("x", typeof(float));
    v4.y = (float)info.GetValue("y", typeof(float));
    v4.z = (float)info.GetValue("z", typeof(float));
    v4.w = (float)info.GetValue("w", typeof(float));

    obj = v4;
    return obj;
    }

    }

    class Color_SS : ISerializationSurrogate
    {
    //Serialize Color
    public void GetObjectData(System.Object obj, SerializationInfo info, StreamingContext context)
    {
    Color color = (Color)obj;
    info.AddValue("r", color.r);
    info.AddValue("g", color.g);
    info.AddValue("b", color.b);
    info.AddValue("a", color.a);
    }
    //Deserialize Color
    public System.Object SetObjectData(System.Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
    {
    Color color = (Color)obj;

    color.r = (float)info.GetValue("r", typeof(float));
    color.g = (float)info.GetValue("g", typeof(float));
    color.b = (float)info.GetValue("b", typeof(float));
    color.a = (float)info.GetValue("a", typeof(float));

    obj = color;
    return obj;
    }
    }

    class Quaternion_SS : ISerializationSurrogate
    {
    //Serialize Quaternion
    public void GetObjectData(System.Object obj, SerializationInfo info, StreamingContext context)
    {
    Quaternion qua = (Quaternion)obj;
    info.AddValue("x", qua.x);
    info.AddValue("y", qua.y);
    info.AddValue("z", qua.z);
    info.AddValue("w", qua.w);
    }
    //Deserialize Quaternion
    public System.Object SetObjectData(System.Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
    {
    Quaternion qua = (Quaternion)obj;

    qua.x = (float)info.GetValue("x", typeof(float));
    qua.y = (float)info.GetValue("y", typeof(float));
    qua.z = (float)info.GetValue("z", typeof(float));
    qua.w = (float)info.GetValue("w", typeof(float));

    obj = qua;
    return obj;
    }
    }
    }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,690
    Don't use the binary formatter/serializer: it is insecure, it cannot be made secure, and it makes debugging very difficult, plus it actually will NOT prevent people from modifying your save data on their computers.

    https://docs.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide

    Beyond that, the complete error message contains everything you need to know to fix the error yourself.

    Always start with the FIRST error in the list, as sometimes that error causes or compounds some or all of the subsequent errors.

    The important parts of the error message are:

    - the description of the error itself (google this; you are NEVER the first one!)
    - the file it occurred in (critical!)
    - the line number and character position (the two numbers in parentheses)

    All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don't have to stop your progress and fiddle around with the forum.

    This may be applicable too: some help to fix "Cannot implicitly convert type 'Xxxxx' into 'Yyyy':"

    http://plbm.com/?p=263

    Finally, if you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/
     
    Bunny83 likes this.
  3. subswithjust1video

    subswithjust1video

    Joined:
    Jun 30, 2021
    Posts:
    2
    But what caused this error and that code isnt a thing i did I taked a yt tutorial and im just a beginner and i dont think i can change there anything with this TAGS im looking for a reply that saying what was wrong and not links to tutorials!
     
    Last edited: Aug 1, 2021
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,690
    As I posted above, don't use binary formatter unless there's some legacy technical issue you're trying to interoperate with. If you're a beginner, I doubt that's the case.

    tl;dir "the code you have above is broke by today's security standards, and that code has ABSOLUTELY NOTHING TO DO WITH UNITY, so I suggest you get different code."

    Here's four great places to start learning Unity:

    Imphenzia / imphenzia - super-basic Unity tutorial:



    Jason Weimann:



    Brackeys super-basic Unity Tutorial series:



    Sebastian Lague Intro to Game Development with Unity and C#:

     
  5. zombiegorilla

    zombiegorilla

    Moderator

    Joined:
    May 8, 2012
    Posts:
    9,051
    Before you post again, please read and follow the rules.
    USE code tags. Post compete information. posting part of the error is a waste of everyone's time. Please read the suggestions posted above, they are helpful and point you in the right direction. Also, please look at the unity Learn section and start with the tutorials there. A beginning jumping into something like a binary serializer is going be problematic.

    Closed.
     
Thread Status:
Not open for further replies.