欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Unity 之 编辑器模拟手机大退重连工具类

程序员文章站 2022-04-01 10:37:05
Unity 之 编辑器模拟手机大退重连工具类...

分享一个曾经用过的在Unity Editor 上模拟小断线的重连的工具类(手机大退再回来),复制代码到你的工程中,然后挂载到任意物体;运行后,即可模拟断线重连了。

源码如下:

using UnityEditor;
using UnityEngine;

public class SwitchToBackground : MonoBehaviour
{
    public void sendApplicationPauseMessage(bool isPause)
    {
        Transform[] transList = GameObject.FindObjectsOfType<Transform>();
        for (int i = 0; i < transList.Length; i++)
        {
            Transform trans = transList[i];
            //Note that messages will not be sent to inactive objects
            trans.SendMessage("OnApplicationPause", isPause, SendMessageOptions.DontRequireReceiver);
        }
    }
    public void sendApplicationFocusMessage(bool isFocus)
    {
        Transform[] transList = GameObject.FindObjectsOfType<Transform>();
        for (int i = 0; i < transList.Length; i++)
        {
            Transform trans = transList[i];
            //Note that messages will not be sent to inactive objects
            trans.SendMessage("OnApplicationFocus", isFocus, SendMessageOptions.DontRequireReceiver);
        }
    }

    public void sendEnterBackgroundMessage()
    {
        sendApplicationPauseMessage(true);
        sendApplicationFocusMessage(false);

    }
    public void sendEnterFoegroundMessage()
    {
        sendApplicationFocusMessage(true);
        sendApplicationPauseMessage(false);

    }

}

[CustomEditor(typeof(SwitchToBackground))]
public class simulateSwitchToBackgroundEditor : Editor
{
    void OnEnable()
    {
    }

    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        serializedObject.Update();

        serializedObject.ApplyModifiedProperties();//now varibles in script have been updated  

        if (GUILayout.Button("send enter background message"))
        {
            if (Application.isPlaying)
            {
                ((SwitchToBackground)target).sendEnterBackgroundMessage();
            }
        }
        if (GUILayout.Button("send enter foeground message"))
        {
            if (Application.isPlaying)
            {
                ((SwitchToBackground)target).sendEnterFoegroundMessage();
            }
        }
    }
}

挂载带场景任意物体上即可。。。
Unity 之 编辑器模拟手机大退重连工具类
PS:一个需要注意的点,打包时需要将代码全部注释,重新编译后重新尝试打包即可,否则会报错,
Unity 之 编辑器模拟手机大退重连工具类

本文地址:https://blog.csdn.net/Czhenya/article/details/110188563