title: Unity C# InvalidCastException: Cannot cast from source type to destination type
body: <p>I'm currently encountering an error in a large scale project.</p>
  
  <p><strong>Code below:</strong></p>
  
  <pre><code>public void SaveFileExists(){
  
      Debug.Log ("SaveFileExists was called.");
  
      //GameObject.Find ("_Scripts").GetComponent&lt;SaveGame&gt; ().Load ();
      UserData userdata = null;
  
      //Creating a new BinaryFormatter
      BinaryFormatter bf = new BinaryFormatter ();
  
      //Making a file which now contains the Un-Serialized File
      FileStream file = File.Open (Application.persistentDataPath + ("/UserData." + accountLoginAttempt), FileMode.Open);
  
      //Assigning the values of the saved file to the new file
      //UserData newData = (UserData)bf.Deserialize (file);
  
      userdata = bf.Deserialize(file) as UserData;
  
      //Assigning the values from the save file to the variables in this script.
      accountLoginAttempt = userdata.username;
      accountLevel = userdata.userlevel;
  
      //Assinging the values from this script to the _PlayerManager script. (This is where the UI gets it's info).
      GameObject.Find ("_AccountInfoSaveHolder").GetComponent&lt;HoldInfo&gt; ().UserInfo = accountLoginAttempt;
      GameObject.Find ("_AccountInfoSaveHolder").GetComponent&lt;HoldInfo&gt; ().UserLevel = accountLevel;
  
      errortext.text = "Login Successful.";
      Canvas.ForceUpdateCanvases ();
  }
  </code></pre>
  
  <p><strong>The serialised field is also below:</strong></p>
  
  <pre><code>[System.Serializable]
  class UserData{
  public string username;
  public int userlevel;
  }
  </code></pre>
  
  <p>I am trying to load a savefile which is stored in the Application.persistentDataPath. Assigning the UserData.username and UserData.userlevel to variables in my script.</p>
  
  <p><strong>The error I am receiving is:</strong></p>
  
  <blockquote>
    <p>InvalidCastException: Cannot cast from source type to destination
    type.</p>
  </blockquote>
  
  <p><strong>Further Details:</strong></p>
  
  <blockquote>
    <p>LoginScript.SaveFileExists () (at
    Assets/Scripts/AccountSystem/LoginScript.cs:126)
    LoginScript.OnLoginClick () (at
    Assets/Scripts/AccountSystem/LoginScript.cs:104)
    UnityEngine.Events.InvokableCall.Invoke (System.Object[] args) (at
    /Users/builduser/buildslave/unity/build/Runtime/Export/UnityEvent.cs:153)
    UnityEngine.Events.InvokableCallList.Invoke (System.Object[]
    parameters) (at
    /Users/builduser/buildslave/unity/build/Runtime/Export/UnityEvent.cs:634)
    UnityEngine.Events.UnityEventBase.Invoke (System.Object[] parameters)
    (at
    /Users/builduser/buildslave/unity/build/Runtime/Export/UnityEvent.cs:769)
    UnityEngine.Events.UnityEvent.Invoke () (at
    /Users/builduser/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:53)
    UnityEngine.UI.Button.Press () (at
    /Users/builduser/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:35)
    UnityEngine.UI.Button.OnPointerClick
    (UnityEngine.EventSystems.PointerEventData eventData) (at
    /Users/builduser/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:44)
    UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler
    handler, UnityEngine.EventSystems.BaseEventData eventData) (at
    /Users/builduser/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:52)
    UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler]
    (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData
    eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at
    /Users/builduser/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:269)
    UnityEngine.EventSystems.EventSystem:Update()</p>
  </blockquote>
  
  <p>EDIT:</p>
  
  <p><strong>SaveGame.cs:</strong></p>
  
  <pre><code>using System.Collections;
  using System.Collections.Generic;
  using UnityEngine;
  using System.Runtime.Serialization.Formatters.Binary; 
  using System.IO;
  using UnityEngine.SceneManagement;
  
  public class SaveGame : MonoBehaviour {
  
  //Saved Variables
  [Header("Saved Variables")]
  public string savedname;
  public string attemptedlogin;
  public int savedlevel;
  
  //Loaded Variables
  [Header("Loaded Variables")]
  public string loadedname;
  public int loadedlevel;
  
  
  public void Awake(){
  
      if (SceneManager.GetActiveScene ().name == "GameScene") {
          Load ();
      }
  }
  
  public void Save(){
  
      savedname = GameObject.Find ("_Scripts").GetComponent&lt;PlayerManager&gt; ().PlayerName;
      savedlevel = GameObject.Find ("_Scripts").GetComponent&lt;PlayerManager&gt; ().UserLevel;
  
      BinaryFormatter bf = new BinaryFormatter();
  
      FileStream file = File.Open(Application.persistentDataPath + ("/UserData." + savedname), FileMode.Create);
  
      UserData newData = new UserData();
  
      newData.username = savedname;
      newData.userlevel = savedlevel;
  
      bf.Serialize(file, newData);
      file.Close();
  }
  }
  </code></pre>
  
  <p>I also removed all System.Serializable class's throughout my scripts and made a script called UserDataSerialize.cs which contains:</p>
  
  <pre><code>using System.Collections;
  using System.Collections.Generic;
  using UnityEngine;
  
  [System.Serializable]
  class UserData{
      public string username;
      public int userlevel;
  }
  </code></pre>
  
  <p>Now the error I get is:</p>
  
  <pre><code>TypeLoadException: Could not load type 'SaveGame+UserData'.
  System.Reflection.Assembly.GetType (System.String name, Boolean throwOnError, Boolean ignoreCase) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/Assembly.cs:398)
  System.Reflection.Assembly.GetType (System.String name, Boolean throwOnError) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/Assembly.cs:381)
  System.Runtime.Serialization.Formatters.Binary.ObjectReader.GetDeserializationType (Int64 assemblyId, System.String className) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs:833)
  System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadTypeMetadata (System.IO.BinaryReader reader, Boolean isRuntimeObject, Boolean hasTypeInfo) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs:637)
  System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObjectInstance (System.IO.BinaryReader reader, Boolean isRuntimeObject, Boolean hasTypeInfo, System.Int64&amp; objectId, System.Object&amp; value, System.Runtime.Serialization.SerializationInfo&amp; info) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs:269)
  System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObject (BinaryElement element, System.IO.BinaryReader reader, System.Int64&amp; objectId, System.Object&amp; value, System.Runtime.Serialization.SerializationInfo&amp; info) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs:195)
  System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObject (BinaryElement element, System.IO.BinaryReader reader, System.Int64&amp; objectId, System.Object&amp; value, System.Runtime.Serialization.SerializationInfo&amp; info) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs:223)
  System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadNextObject (BinaryElement element, System.IO.BinaryReader reader) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs:130)
  System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObjectGraph (BinaryElement elem, System.IO.BinaryReader reader, Boolean readHeaders, System.Object&amp; result, System.Runtime.Remoting.Messaging.Header[]&amp; headers) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs:104)
  System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.NoCheckDeserialize (System.IO.Stream serializationStream, System.Runtime.Remoting.Messaging.HeaderHandler handler) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/BinaryFormatter.cs:179)
  System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize (System.IO.Stream serializationStream) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/BinaryFormatter.cs:136)
  LoginScript.SaveFileExists () (at Assets/Scripts/AccountSystem/LoginScript.cs:111)
  LoginScript.OnLoginClick () (at Assets/Scripts/AccountSystem/LoginScript.cs:84)
  UnityEngine.Events.InvokableCall.Invoke (System.Object[] args) (at /Users/builduser/buildslave/unity/build/Runtime/Export/UnityEvent.cs:153)
  UnityEngine.Events.InvokableCallList.Invoke (System.Object[] parameters) (at /Users/builduser/buildslave/unity/build/Runtime/Export/UnityEvent.cs:634)
  UnityEngine.Events.UnityEventBase.Invoke (System.Object[] parameters) (at /Users/builduser/buildslave/unity/build/Runtime/Export/UnityEvent.cs:769)
  UnityEngine.Events.UnityEvent.Invoke () (at /Users/builduser/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:53)
  UnityEngine.UI.Button.Press () (at /Users/builduser/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:35)
  UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at /Users/builduser/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:44)
  UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at /Users/builduser/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:52)
  UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at /Users/builduser/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:269)
  UnityEngine.EventSystems.EventSystem:Update()
  </code></pre>