Encounter / Assets / Scripts / GUIHandlers / LoadingScene.cs
LoadingScene.cs
Raw
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;

/// <summary>
/// Handles the loading scene functionality
/// </summary>
public class LoadingScene : MonoBehaviour
{
    [Header("Loading Screen Aspects")]
    [SerializeField] private List<string> funnyLoadSentences;
    [SerializeField] private TextMeshProUGUI loadingSentenceField;
    [SerializeField] private Vector2 durationOfSentence;
    [SerializeField] private GameObject loadingScreenObject;
    [SerializeField] private Image loadingBarImage;

    private float totalViewTime = 0.0f;
    private string currentString;

    public void LoadScene(int sceneId, Canvas creationCanvas)
        => StartCoroutine(LoadSceneAsync(sceneId, creationCanvas));

    private IEnumerator LoadSceneAsync(int sceneId, Canvas creationCanvas)
    {
        AsyncOperation operation = SceneManager.LoadSceneAsync(sceneId);
        
        currentString = funnyLoadSentences[Random.Range(0, funnyLoadSentences.Count)];
        loadingSentenceField.text = currentString;
        loadingScreenObject.SetActive(true);
        creationCanvas.transform.GetChild(0).gameObject.SetActive(false);
        float currentDuration = Random.Range(durationOfSentence.x, durationOfSentence.y);

        while (!operation.isDone)
        {
            float progressValue                 = Mathf.Clamp01(operation.progress / 0.9f);
            loadingBarImage.fillAmount          = progressValue;

            if (totalViewTime >= currentDuration)
            {
                string newCurrentString;

                do
                {
                    newCurrentString         = funnyLoadSentences[Random.Range(0, funnyLoadSentences.Count)];
                } 
                while (newCurrentString.Equals(currentString));

                currentDuration                 = Random.Range(durationOfSentence.x, durationOfSentence.y);
                loadingSentenceField.text       = newCurrentString;
                currentString                   = newCurrentString;
                totalViewTime                   = 0.0f;
            }

            totalViewTime += Time.deltaTime;
            yield return null;
        }
    }
}