Advertisement
Guest User

Untitled

a guest
Jun 28th, 2020
602
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.85 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System;
  5. using UnityEngine.SceneManagement;
  6.  
  7. namespace shakagamii.Game {
  8.  
  9.     //Реализуем шаблонный класс Singlton`a
  10.     public class Singleton<T> where T : class, new() {
  11.  
  12.         private static readonly Lazy<T> _instance = new Lazy<T>(() => new T());
  13.         public static T Instance => _instance.Value;
  14.         public bool HasInstance => Instance != null;
  15.     }
  16.  
  17.     //Реализуем простой Singlton менеджер
  18.     //для одного значенияздоровья персонажа
  19.     public class PlayerDataManager : Singleton<PlayerDataManager> {
  20.  
  21.         public static Action<float> OnHealthChanged = default;
  22.         private float _healthAmount;
  23.  
  24.         public static float HealthAmount {
  25.             get => Instance._healthAmount;
  26.             set {
  27.                 Instance._healthAmount = Mathf.Clamp(value, 0f, 100f);
  28.                 OnHealthChanged?.Invoke(Instance._healthAmount);
  29.             }
  30.         }
  31.     }
  32.  
  33.     //И используем его так
  34.     //В одной сцене заносим данные, и переходим в другую
  35.     public class Scene01SceneChangeScript : MonoBehaviour {
  36.  
  37.         public float PlayerHealAmount = 100f;
  38.  
  39.         public IEnumerator Start() {
  40.             PlayerDataManager.HealthAmount = PlayerHealAmount;
  41.             yield return new WaitForSeconds(2f);
  42.             SceneManager.LoadSceneAsync("Scene02");
  43.         }
  44.     }
  45.  
  46.     //Во второй следовательно эти данные тянем обратно.
  47.     public class Scene02SceneChangeScript : MonoBehaviour {
  48.  
  49.         public float PlayerHealAmount;
  50.  
  51.         public IEnumerator Start() {
  52.             PlayerHealAmount = PlayerDataManager.HealthAmount;
  53.             yield return null;
  54.         }
  55.     }
  56.  
  57.     //Реализуем менеджер на основе MonoBehaviour
  58.     //И используем DontDestroyOnLoad для того
  59.     //чтобы объект не уничтожался при переходе меж сценами
  60.     public class PlayerDataMonoManager : MonoBehaviour {
  61.  
  62.         public static Action<float> OnHealthChanged = default;
  63.         [SerializeField]
  64.         private static float  _healthAmount;
  65.  
  66.         public void Awake() {
  67.             DontDestroyOnLoad(this);
  68.         }
  69.  
  70.         public static float HealthAmount {
  71.             get => _healthAmount;
  72.             set {
  73.                 _healthAmount = Mathf.Clamp(value, 0f, 100f);
  74.                 OnHealthChanged?.Invoke(_healthAmount);
  75.             }
  76.         }
  77.     }
  78.  
  79.     public class PlayerData {
  80.  
  81.         public static Action<float> OnHealthChanged = default;
  82.  
  83.         private static float _healthAmount = 100f;
  84.  
  85.         public static float HealthAmount {
  86.             get => _healthAmount;
  87.             set {
  88.                 _healthAmount = Mathf.Clamp(value, 0f, 100f);
  89.                 OnHealthChanged?.Invoke(_healthAmount);
  90.             }
  91.         }
  92.     }
  93.  
  94.     //Реализуем наше так называемое ядро игры
  95.     public class Core {
  96.  
  97.         private Core _instance;
  98.         private MonoCore _mono;
  99.  
  100.         public static PlayerData PlayerData;
  101.  
  102.         private Core(MonoCore mono) {
  103.             _mono = mono;
  104.             PlayerData = new PlayerData();
  105.         }
  106.  
  107.         public Core Create(MonoCore mono) {
  108.             return _instance ?? _instance = new Core(mono);
  109.         }
  110.  
  111.     }
  112.  
  113.     //Реализуем инициализацию ядра
  114.     //Помещаем скрипт на любой объект сцены SceneCore
  115.     public class MonoCore : MonoBehaviour {
  116.  
  117.         public Core Core;
  118.  
  119.         public void Awake() {
  120.             Core = Core.Create(this);
  121.         }
  122.        
  123.     }
  124.  
  125.     //Скрипт на сцене 1, тянем дату, записыываем новое значение
  126.     //ждем пару секунд, переходим на следующую сцену
  127.     public class Scene01SceneChangeScript : MonoBehaviour {
  128.  
  129.         public PlayerData PlayerData;
  130.  
  131.         public IEnumerator Start() {
  132.             PlayerData = Core.PlayerData;
  133.             PlayerData.HealthAmount = 99f;
  134.             yield return new WaitForSeconds(2f);
  135.             StartScene02();
  136.         }
  137.  
  138.         public void StartScene02() {
  139.             AsyncOperation loadOperation = SceneManager.LoadSceneAsync("Scene02", LoadSceneMode.Additive);
  140.             loadOperation.allowSceneActivation = true;
  141.             loadOperation.completed += (operation) => SceneManager.UnloadSceneAsync("Scene01");
  142.         }
  143.  
  144.     }
  145.  
  146.     //Во второй следовательно эти данные тянем обратно.
  147.     public class Scene02SceneChangeScript : MonoBehaviour {
  148.  
  149.         public PlayerData PlayerData;
  150.    
  151.         public IEnumerator Start() {
  152.             PlayerData = Core.PlayerData;
  153.             yield return null;
  154.         }
  155.     }
  156.  
  157.     //Просто кидаете файл с кодом в любую папку, и
  158.     //он будет автоматически срабатывать при запуске редактора
  159.     //или изменении списка сцен в настройках
  160.     [InitializeOnLoad]
  161.     public class PlayModeStartSceneSetup {
  162.  
  163.         public const float START_SCENE_INDEX = 0f;
  164.      
  165.         static PlayModeStartSceneSetup() {
  166.  
  167.             SceneListChanged();
  168.             EditorBuildSettings.sceneListChanged += SceneListChanged;
  169.  
  170.         }
  171.  
  172.         static void SceneListChanged() {
  173.  
  174.             if (EditorBuildSettings.scenes.Length == 0) return;
  175.             SceneAsset scene = AssetDatabase.LoadAssetAtPath<SceneAsset>(EditorBuildSettings.scenes[START_SCENE_INDEX].path);
  176.             EditorSceneManager.playModeStartScene = scene;
  177.  
  178.         }
  179.  
  180.     }
  181. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement