Unity切换场景保存上一个场景的数据,Unity切换场景的案例,Unity切换场景再返回数据丢失的解决方案

问题:

Unity在切换场景之后在再次返回上不会保存上一个场景的数据的。
但是大多数时候我们是需要这些数据的,这应该如何解决呢?

解决方案:

  1. 文件链接:我将解决方案打包了,点我下载,免费,或者私信我发你
  2. 首先将需要存储到一个class中,这里以学生为例子
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

namespace ScenceChange
{
    [Serializable]
    public class StudentEnity
    {
        public string Name;
        public string Description;
        public float _Time;
    }
}


  1. 然后我们再创建一个脚本,并这个脚本挂到Unity场景中的游戏物体上.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace ScenceChange
{
    public class tudentGaemObject : MonoBehaviour
    {
        public StudentEnity StudentEnity;
        public int No;

        private void Start()
        {
            var stu = GameManger._Instance.students.FirstOrDefault(p => p.Name == StudentEnity.Name);
            if (stu != null)
            {
                StudentEnity = stu;
            }
            else
            {
                GameManger._Instance.AddStudent(StudentEnity);
            }
            // UI 显示对应的student属性内容
        }

        private void Update()
        {
            StudentEnity._Time = StudentEnity._Time + Time.deltaTime;
        }
    }
}

GameManager中的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace ScenceChange
{
    public class GameManger : SingletonBase
    {
        public List students;
        private void Awake()
        {
            DontDestroyOnLoad(this);
            students = new List();
        }

        public void AddStudent(StudentEnity student)
        {
            if (!students.Contains(student))
            {
                students.Add(student);
            }
        }
    }
}

SingletonBase中的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace ScenceChange
{
    public class GameManger : SingletonBase
    {
        public List students;
        private void Awake()
        {
            DontDestroyOnLoad(this);
            students = new List();
        }

        public void AddStudent(StudentEnity student)
        {
            if (!students.Contains(student))
            {
                students.Add(student);
            }
        }
    }
}
  1. 在上面我们完成了数据载体的创建(StudentEnity,tudentGaemObject ),以及场景切换的时候用于保存数据的载体(GameManger ,StudentEnity)。
  2. 接下来我们做一些场景切换的工作,创建两个场景,一个名字为"ScenceA",另外一个为“ScenceB“,分别在场景中创建一个Button,场景A的按钮挂在这个脚本
 private void Awake()
        {
            Button but=gameObject.GetComponent

场景B挂载这个脚本

        private void Awake()
        {
            Button but = gameObject.GetComponent

然后点击按钮就会跳转场景。

  1. 然后测试一下就会发现场景跳转 StudentEnity中的_Time还是会按照跳转之前的继续增加。

Enjoy ,不懂私信,我会看。

你可能感兴趣的:(Unity,unity,C#)