Unity 场景切换时,相同的后台通信和数据处理逻辑必须保持一致,但部分场景数据在切换时丢失。
以现有通信框架为例, 不同需求的数据接收对应不同的代码,后台通信部分需要每次直接在核心源代码中重写,能否设计一种固定不变的后台服务器通信框架,使每次使用时只在应用程序部分修改?
思路:
将后台通信部分设置为静态, 每次都能全局调用,只初始化一次;同时数据接收部分只有框架,具体的接收相应函数每次单独设置。
在应用脚本中调用后台数据
实例:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BaseClass : MonoBehaviour
{
// Start is called before the first frame update
public event Action<int> OnStart;
public event Action OnStop;
public Action <int> OnUpdate;
public event Action<float []> OnNewSample;
private void Update()
{
if (OnUpdate != null)
{
Debug.Log("not null onupdate");
OnUpdate(123);
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class App : MonoBehaviour
{
public BaseClass source;
// Start is called before the first frame update
void Start()
{
// source.OnStart += OnStartStreaming;
// source.OnUpdate += OnUpdate;
}
private void OnUpdate(int a)
{
Debug.Log("OnUpdate");
}
private void OnStartStreaming(int a)
{
Debug.Log("OnStartStreaming");
}
// Update is called once per frame
void OnGUI()
{
if(GUI.Button(new Rect(100,100,100,100), "set event"))
{
source.OnUpdate += OnUpdate;
if(source.OnUpdate.h)
}
if (GUI.Button(new Rect(100, 300, 100, 100), "delete event"))
{
source.OnUpdate -= OnUpdate;
}
}
}
通信框架设置
接收部分的processInput 具体实现设置为应用脚本动态设置,自身存在于后台update中