You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-Native嵌入iOS的Unity应用调用unload后无法重连PhotonNetwork

iOS嵌入Unity多次启动后Photon Pun无法连接的解决方案

问题核心

React Native开发的iOS应用嵌入Unity后,多次打开/关闭Unity时,Photon Pun因PhotonHandler单例在首次启动后被禁用,再次启动时未重新启用而无法连接服务器。原因是PhotonNetwork的静态构造函数仅执行一次,PhotonHandler实例已存在但处于禁用状态。

解决方案

方案1:Unity端添加Photon清理逻辑,退出时重置单例

在Unity中创建清理脚本,在React Native触发Unity卸载前执行,彻底重置Photon的状态:

using UnityEngine;
using System.Reflection;
using Photon.Pun;

public class PhotonRestartCleanup : MonoBehaviour
{
    // 让React Native通过UnitySendMessage调用此方法
    public static void PrepareForUnload()
    {
        // 断开现有连接
        if (PhotonNetwork.IsConnected)
        {
            PhotonNetwork.Disconnect();
        }

        // 重置PhotonNetwork核心状态
        PhotonNetwork.StaticReset();

        // 通过反射清除PhotonHandler单例,强制下次启动重新创建
        var handlerType = typeof(PhotonHandler);
        var instanceField = handlerType.GetField("instance", BindingFlags.Static | BindingFlags.NonPublic);
        if (instanceField != null)
        {
            var handlerInstance = instanceField.GetValue(null) as PhotonHandler;
            if (handlerInstance != null)
            {
                Destroy(handlerInstance.gameObject);
            }
            instanceField.SetValue(null, null);
        }
    }
}

使用方式:

  • 将脚本挂载到一个DontDestroyOnLoad的GameObject上
  • 在React Native调用unityFramework.unloadApplication()之前,通过UnitySendMessage触发PhotonRestartCleanup.PrepareForUnload()

方案2:Unity启动时手动检查并启用PhotonHandler

在你的Photon管理脚本(如PhotonManager)中,添加启动时的状态检查,手动启用被禁用的PhotonHandler并重置:

using Photon.Pun;
using UnityEngine;

public class PhotonManager : MonoBehaviour
{
    private void OnEnable()
    {
        // 检查PhotonHandler状态
        if (PhotonHandler.Instance != null && !PhotonHandler.Instance.enabled)
        {
            // 重新启用PhotonHandler
            PhotonHandler.Instance.enabled = true;
            // 重置PhotonNetwork配置
            PhotonNetwork.StaticReset();
            // 重新加载服务器配置(根据你的项目调整)
            PhotonNetwork.PhotonServerSettings.AppSettings.AppId = "你的Photon AppId";
        }

        // 执行正常连接逻辑
        if (!PhotonNetwork.IsConnected)
        {
            PhotonNetwork.ConnectUsingSettings();
        }
    }
}

方案3:iOS端优化Unity卸载流程(辅助)

iOS不支持像Android那样的多进程隔离,但可以在卸载Unity后尝试清理残留的静态资源:

  • 调用unityFramework.unloadApplication()后,将unityFramework实例置为nil,下次启动时重新初始化UnityFramework:
// 卸载Unity后
unityFramework.unloadApplication()
unityFramework = nil

// 下次启动时重新初始化
unityFramework = UnityFramework.getInstance()
unityFramework?.runEmbedded(withArgc: CommandLine.argc, argv: CommandLine.unsafeArgv, appLaunchOpts: [:])

注意事项

  • 确保所有Photon相关的协程、回调在卸载前停止,避免内存泄漏
  • 测试时需验证多次启动/关闭后PhotonHandler的enabled状态是否正常
  • 若使用Photon的自定义配置,需在重置后重新加载对应配置

内容的提问来源于stack exchange,提问作者romixch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 15:00:45