菜鸟教程小白 发表于 2022-12-12 13:38:52

ios - 保存和加载游戏数据不起作用


                                            <p><p>不知道为什么我的代码不起作用,因为我遵循了我找到的示例。试图让我的 iOS 游戏使用 Unity3D 保存和加载数据,但不使用 player.prefs。</p>

<p>在现场我有这个</p>

<pre><code>void OnDisable(){
    GameController.Save ();
}

void OnEable(){
    GameController.Load ();
}
</code></pre>

<p>游戏 Controller 是一个静态方法.. </p>

<pre><code>static public void Save()
    {
      Debug.Log(&#34;Saving Player Data...&#34;);
      print (&#34;Saving Player Data...&#34;);
      var bf = new BinaryFormatter();
      var file = File.Create(Application.persistentDataPath + &#34;/CatEscapeInfo.dat&#34;);

      var data = new PlayerData
      {
            PlayerLives = PlayerLives,
            Score = Score,
            Distance = Distance,
            CurrentLevelNo = CurrentLevelNo,
            HighestLevelCompleted = HighestLevelCompleted
      };

      bf.Serialize(file, data);
      file.Close();
      //PlayerPrefs.SetString (data);
      Debug.Log (&#34;Player Data Saved: &#34; + PlayerLives + &#34;, &#34; + Score);
      print (&#34;Player Data Saved: &#34; + PlayerLives + &#34;, &#34; + Score);
    }

    static public void Load()
    {
      Debug.Log(&#34;Loading Player Data...&#34;);
      if (File.Exists(Application.persistentDataPath + &#34;/CatEscapeInfo.dat&#34;))
      {
            var bf = new BinaryFormatter();
            var file = File.Open(Application.persistentDataPath + &#34;/CatEscapeInfo.dat&#34;, FileMode.Open);
            var data = bf.Deserialize(file) as PlayerData;
            file.Close();

            Debug.Log(&#34;Player Data Loaded: &#34; + data.PlayerLives + &#34;, &#34; + data.Score);
            print (&#34;Player Data Loaded: &#34; + data.PlayerLives + &#34;, &#34; + data.Score);

            if (data != null)
            {
                PlayerLives = data.PlayerLives;
                Score = data.Score;
                Distance = data.Distance;
                CurrentLevelNo = data.CurrentLevelNo;
                HighestLevelCompleted = data.HighestLevelCompleted;
            }
      }
    }
</code></pre>

<p>即使我运行了这段代码,但当我在 iOS 上手动关闭游戏并将其恢复时,它永远不会将游戏加载回原来的状态。
有什么想法吗?我错过了什么吗?</p>

<p>更新:
在 iOS XCode 中,我发现它在尝试“加载”时会吐出这个堆栈跟踪,尽管此时文件还不存在。</p>

<p><strong>加载时这是堆栈跟踪:</strong></p>

<pre><code>&gt; (Filename:
&gt; /Applications/buildAgent/work/d63dfc6385190b60/artifacts/iPhonePlayer-armv7Generated/UnityEngineDebug.cpp
&gt; Line: 49)
&gt;
&gt; SerializationException: Unexpected binary element: 255   at
&gt; System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObject
&gt; (BinaryElement element, System.IO.BinaryReader reader, System.Int64&amp;
&gt; objectId, System.Object&amp; value,
&gt; System.Runtime.Serialization.SerializationInfo&amp; info) in
&gt; &lt;filename unknown&gt;:0    at
&gt; System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadNextObject
&gt; (BinaryElement element, System.IO.BinaryReader reader) in
&gt; &lt;filename unknown&gt;:0    at
&gt; System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObjectGraph
&gt; (BinaryElement elem, System.IO.BinaryReader reader, Boolean
&gt; readHeaders, System.Object&amp; result,
&gt; System.Runtime.Remoting.Messaging.Header[]&amp; headers) in
&gt; &lt;filename unknown&gt;:0    at
&gt; System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.NoCheckDeserialize
&gt; (System.IO.Stream serializationStream,
&gt; System.Runtime.Remoting.Messaging.HeaderHandler handler) in
&gt; &lt;filename unknown&gt;:0    at
&gt; System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize
&gt; (System.IO.Stream serializationStream) in &lt;filename
&gt; unknown&gt;:0    at GameController.Load () in &lt;filename
&gt; unknown&gt;:0    at GameController.OnEnable () in &lt;filename
&gt; unknown&gt;:0    (Filename:Line: -1)
</code></pre>

<p><strong>保存时,这是堆栈跟踪:</strong></p>

<pre><code>&gt; Saving Player Data... UnityEngine.Debug:Internal_Log(Int32, String,
&gt; Object) UnityEngine.Debug:Log(Object)
&gt; UnityEngine.MonoBehaviour:print(Object) GameController:Save()
&gt; GameController:OnDisable() UnityEngine.Object:Destroy(Object, Single)
&gt; UnityEngine.Object:Destroy(Object) GameController:Awake()   (Filename:
&gt; /Applications/buildAgent/work/d63dfc6385190b60/artifacts/iPhonePlayer-armv7Generated/UnityEngineDebug.cpp
&gt; Line: 49)
&gt;
&gt; ExecutionEngineException: Attempting to JIT compile method
&gt; &#39;PlayerData__TypeMetadata4:.ctor ()&#39; while running with --aot-only.
&gt;
&gt;   at System.Reflection.MonoCMethod.Invoke (System.Object obj,
&gt; BindingFlags invokeAttr, System.Reflection.Binder binder,
&gt; System.Object[] parameters, System.Globalization.CultureInfo culture)
&gt; in &lt;filename unknown&gt;:0Rethrow as
&gt; TargetInvocationException: Exception has been thrown by the target of
&gt; an invocation.   at System.Reflection.MonoCMethod.Invoke
&gt; (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder
&gt; binder, System.Object[] parameters, System.Globalization.CultureInfo
&gt; culture) in &lt;filename unknown&gt;:0    at
&gt; System.Reflection.MonoCMethod.Invoke (BindingFlags invokeAttr,
&gt; System.Reflection.Binder binder, System.Object[] parameters,
&gt; System.Globalization.CultureInfo culture) in &lt;filename
&gt; unknown&gt;:0    at System.Reflection.ConstructorInfo.Invoke
&gt; (System.Object[] parameters) in &lt;filename unknown&gt;:0    at
&gt; System.Activator.CreateInstance (System.Type type, Boolean nonPublic)
&gt; in &lt;filename unknown&gt;:0    at
&gt; System.Activator.CreateInstance (System.Type type) in
&gt; &lt;filename unknown&gt;:0    at
&gt; System.Runtime.Serialization.Formatters.Binary.ObjectWriter.CreateMemberTypeMetadata
&gt; (System.Type type) in &lt;filename unknown&gt;:0    at
&gt; System.Runtime.Serialization.Formatters.Binary.ObjectWriter.GetObjectData
&gt; (System.Object obj,
&gt; System.Runtime.Serialization.Formatters.Binary.TypeMetadata&amp; metadata,
&gt; System.Object&amp; data) in &lt;filename unknown&gt;:0    at
&gt; System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteObject
&gt; (System.IO.BinaryWriter writer, Int64 id, System.Object obj)
&gt; in &lt;filename unknown&gt;:0    at
&gt; System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteObjectInstance
&gt; (System.IO.BinaryWriter writer, System.Object obj, Boolean
&gt; isValueObject) in &lt;filename unknown&gt;:0    at
&gt; System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteQueuedObjects
&gt; (System.IO.BinaryWriter writer) in &lt;filename unknown&gt;:0   
&gt; at
&gt; System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteObjectGraph
&gt; (System.IO.BinaryWriter writer, System.Object obj,
&gt; System.Runtime.Remoting.Messaging.Header[] headers) in
&gt; &lt;filename unknown&gt;:0    at
&gt; System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize
&gt; (System.IO.Stream serializationStream, System.Object graph,
&gt; System.Runtime.Remoting.Messaging.Header[] headers) in
&gt; &lt;filename unknown&gt;:0    at
&gt; System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize
&gt; (System.IO.Stream serializationStream, System.Object graph)
&gt; in &lt;filename unknown&gt;:0    at GameController.Save () in
&gt; &lt;filename unknown&gt;:0    at GameController.OnDisable () in
&gt; &lt;filename unknown&gt;:0UnityEngine.Object:Destroy(Object, Single)
&gt; UnityEngine.Object:Destroy(Object) GameController:Awake()
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>将此代码放入场景脚本中的 <code>Awake</code> 或 <code>Start</code> 函数中:</p>

<pre class="lang-cs prettyprint-override"><code>// Forces a different code path in the BinaryFormatter that doesn&#39;t rely on run-time code generation (which would break on iOS).
Environment.SetEnvironmentVariable(&#34;MONO_REFLECTION_SERIALIZER&#34;, &#34;yes&#34;);
</code></pre>

<p>默认情况下,Mono 二进制序列化器使用 iOS 不支持的 JIT 编译。幸运的是,有一种方法(上面的代码)可以将其切换为使用反射。</p>

<p>证明/参见:</p>

<ul>
<li><p> <a href="http://answers.unity3d.com/questions/725419/filestream-binaryformatter-from-c-to-ios-doesnt-wo.html" rel="noreferrer noopener nofollow">http://answers.unity3d.com/questions/725419/filestream-binaryformatter-from-c-to-ios-doesnt-wo.html</a> </p></li>
<li><p> <a href="http://answers.unity3d.com/questions/30930/why-did-my-binaryserialzer-stop-working.html" rel="noreferrer noopener nofollow">http://answers.unity3d.com/questions/30930/why-did-my-binaryserialzer-stop-working.html</a> </p></li>
</ul></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 保存和加载游戏数据不起作用,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/27806113/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/27806113/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 保存和加载游戏数据不起作用