Advertisement
EmmyDev

Level Loader

Jul 2nd, 2023
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.39 KB | Source Code | 0 0
  1. using System.Collections;
  2. using Audio;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.SceneManagement;
  6. using InteractionSystem;
  7. using Movement;
  8.  
  9. public class LevelLoader : Interactable
  10. {
  11.     [Header("Level to load by name")]
  12.     public string levelToLoad;
  13.     [Header("Time to fade in and out")]
  14.     [SerializeField] private float fadeOutTime;
  15.     [SerializeField] private float fadeInTime;
  16.     [SerializeField] private LoaderType loaderType;
  17.     [Header("")]
  18.  
  19.     [SerializeField] private BoxCollider2D collider;
  20.  
  21.     [SerializeField] private bool customLocationWhenLoaded;
  22.     [SerializeField] private Vector2 loadedInPos;
  23.  
  24.     public bool active;
  25.    
  26.     [Header("Optional")]
  27.     [SerializeField] private PlayOneShot _playOneShot;
  28.    
  29.     private FreeMovement player;
  30.     private Canvas _canvas;
  31.     private Image _fadeImg;
  32.     private bool _hasFadedOut;
  33.    
  34.     private bool _beenUsed;
  35.  
  36.     public LoaderType LoaderType => loaderType;
  37.  
  38.    
  39.     private GameObject newLevelPlayerRef;
  40.  
  41.     public override void Interact(PlayerInteract player)
  42.     {
  43.         if (loaderType != LoaderType.Interact) return;
  44.         if(active && _beenUsed == false)
  45.         {
  46.             LoadLevelInit();
  47.             player.SuccessfulInteraction();
  48.             SuccessfulInteraction();
  49.         }
  50.         else
  51.         {
  52.             player.FailedInteraction();
  53.             FailedInteraction();
  54.         }
  55.     }
  56.  
  57.     public bool IsInteractable()
  58.     {
  59.         if (loaderType != LoaderType.Interact) return false;
  60.         return (active && !_beenUsed);
  61.     }
  62.  
  63.     private void Awake()
  64.     {
  65.         player = FindObjectOfType<FreeMovement>();
  66.     }
  67.  
  68.     private void OnEnable()
  69.     {
  70.         player.OnMove += AttemptLoadLevel;
  71.     }
  72.        
  73.     private void OnDisable()
  74.     {
  75.         player.OnMove -= AttemptLoadLevel;
  76.     }
  77.  
  78.     private void AttemptLoadLevel()
  79.     {
  80.         if (!active) return;
  81.         if (loaderType != LoaderType.Proximity) return;
  82.         Rect rect = new Rect(this.transform.position.x + collider.offset.x - (collider.size.x / 2), this.transform.position.y + collider.offset.y - (collider.size.y / 2), collider.size.x, collider.size.y);
  83.         if (rect.Contains(player.transform.position))
  84.         {
  85.             LoadLevelInit();
  86.         }
  87.         //if (Vector3.Distance(player.DiscretePosition, transform.position) <= 1f && _beenUsed == false)
  88.         //{
  89.         //    LoadLevelInit();
  90.         //}
  91.     }
  92.  
  93.     private void LoadLevelInit()
  94.     {
  95.         //Disable further interactions
  96.         _beenUsed = true;
  97.         //disable player movement
  98.         GameObject thisLevelPlayerRef = GameObject.Find("Protagonist");
  99.         thisLevelPlayerRef.GetComponent<FreeMovement>().enabled = false;
  100.         //reset values
  101.         _hasFadedOut = false;
  102.         //Instantiate objects from path
  103.         var fadeEffect = Resources.Load("FadeEffect");
  104.         GameObject fadeInstance = Instantiate(fadeEffect) as GameObject;
  105.         this.transform.SetParent(null);
  106.         DontDestroyOnLoad(fadeInstance);
  107.         DontDestroyOnLoad(this.gameObject);
  108.        
  109.         _canvas = fadeInstance.GetComponent<Canvas>();
  110.         _fadeImg = _canvas.GetComponentInChildren<Image>();
  111.         //start operations
  112.         StartCoroutine(LoadLevelAsync());
  113.         StartCoroutine(Fade(fadeOutTime, 0, 1));
  114.  
  115.  
  116.         if (_playOneShot) _playOneShot.Play();
  117.     }
  118.  
  119.     //coroutine to load level
  120.     IEnumerator LoadLevelAsync()
  121.     {
  122.         AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(levelToLoad);
  123.         asyncLoad.allowSceneActivation = false;
  124.         // Wait until the asynchronous scene fully loads and the fade is done
  125.         while (asyncLoad.progress < 0.9f || !_hasFadedOut)
  126.         {
  127.             yield return null;
  128.         }
  129.         //loads the new scene and fades back in
  130.         asyncLoad.allowSceneActivation = true;
  131.         StartCoroutine(Fade(fadeInTime, 1,0));
  132.        
  133.         active = false;
  134.        
  135.         yield return null;
  136.     }
  137.  
  138.     //coroutine to fade img
  139.     IEnumerator Fade(float seconds, float startVal, float finalVal)
  140.     {
  141.        
  142.         float elapsedTime = 0;
  143.         float alphaVal = startVal;
  144.         //lerp color from startVal to finalVal
  145.         while (elapsedTime < seconds)
  146.         {
  147.             alphaVal = Mathf.Lerp(startVal, finalVal, (elapsedTime / seconds));
  148.             elapsedTime += Time.deltaTime;
  149.            
  150.             if(finalVal == 0f && customLocationWhenLoaded)
  151.             {
  152.  
  153.                 //search for player until level is completely loaded then set their pos. Stop once the level is fully in
  154.                 newLevelPlayerRef = GameObject.Find("Protagonist");
  155.                 if(newLevelPlayerRef != null)
  156.                 {
  157.                     newLevelPlayerRef.transform.position = new Vector3(loadedInPos.x, loadedInPos.y, newLevelPlayerRef.transform.position.z);
  158.                 }
  159.                
  160.  
  161.                 if(SceneManager.GetActiveScene().name == levelToLoad)
  162.                 {
  163.                     customLocationWhenLoaded = false;
  164.                 }
  165.                
  166.             }
  167.            
  168.             //Updates alpha value of the image
  169.             _fadeImg.color = new Color(_fadeImg.color.r, _fadeImg.color.g, _fadeImg.color.b, alphaVal);
  170.             yield return null;
  171.         }
  172.         if(finalVal == 1)
  173.         {
  174.             //tells level loader that fade out has happened
  175.             _hasFadedOut = true;
  176.         }
  177.         else
  178.         {
  179.             //if fade in is done terminate entire process
  180.  
  181.            
  182.  
  183.             Destroy(_canvas.gameObject);
  184.             Destroy(this.gameObject);
  185.         }
  186.         yield return null;
  187.     }
  188.  
  189.     private void OnDrawGizmos()
  190.     {
  191.        
  192.         if(active)
  193.         {
  194.             DrawRect(new Rect(this.transform.position.x + collider.offset.x - (collider.size.x / 2), this.transform.position.y + collider.offset.y - (collider.size.y / 2), collider.size.x, collider.size.y));
  195.             Gizmos.DrawIcon(transform.position, "LVLgizmoBLU.png", true);
  196.         }
  197.         else
  198.         {
  199.             Gizmos.DrawIcon(transform.position, "LVLgizmoRED.png", true);
  200.         }
  201.        
  202.     }
  203.     void DrawRect(Rect rect)
  204.     {  
  205.         Gizmos.DrawWireCube(new Vector3(rect.center.x, rect.center.y, 0.01f), new Vector3(rect.size.x, rect.size.y, 0.01f));
  206.     }
  207.  
  208. }
  209.  
  210. public enum LoaderType
  211. {
  212.     Interact,
  213.     Proximity
  214. }
  215.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement