gather-and-defend/Assets/Scripts/LoadingScreen.cs
2023-10-31 21:06:05 -04:00

83 lines
2.5 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GatherAndDefend.Events;
#if UNITY_EDITOR
using UnityEditor;
[CustomEditor(typeof(LoadingScreen))]
public class LoadingScreenEditor : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
if (!Application.isPlaying) return;
if (GUILayout.Button("start"))
{
(target as LoadingScreen).ShowLoadingScreen();
}
else if (GUILayout.Button("stop"))
{
(target as LoadingScreen).HideLoadingScreen();
}
}
}
#endif
/// <summary>
/// the view-model associated with the loading screen view.
/// </summary>
public class LoadingScreen : SingletonBehaviour<LoadingScreen>
{
[Header("Screen")]
public CanvasGroup blueScreen;
public float fadeInDuration = 1;
public float fadeOutDuration = 1;
public GameObject cloudPrefab;
public int maxClouds = 10;
public CloudAnimation.Properties cloudProperties;
private List<CloudAnimation> clouds = new List<CloudAnimation>();
private Coroutine screenCoroutine, cloudCoroutine;
private IEnumerator SpawnClouds()
{
while (true)
{
var randPos = Extensions.RandomInRectangle(Screen.width + 100, Screen.height - 100);
var cloudInstance = Instantiate(cloudPrefab, randPos, Quaternion.identity);
cloudInstance.transform.SetParent(transform);
var cloudComponent = cloudInstance.GetComponent<CloudAnimation>();
cloudComponent.properties = cloudProperties;
clouds.Add(cloudComponent);
yield return new WaitForSeconds(fadeInDuration);
}
}
private IEnumerator EnableLoadingScreen()
{
yield return blueScreen.FadeTo(1, fadeInDuration);
EventAggregator.Instance.GetEvent<ScreenActivatedEvent>().Invoke();
}
private IEnumerator DisableLoadingScreen()
{
yield return blueScreen.FadeTo(0, fadeOutDuration);
EventAggregator.Instance.GetEvent<ScreenDeactivatedEvent>().Invoke();
}
public void ShowLoadingScreen()
{
screenCoroutine = StartCoroutine(EnableLoadingScreen());
cloudCoroutine = StartCoroutine(SpawnClouds());
}
public void HideLoadingScreen()
{
StopCoroutine(screenCoroutine);
StopCoroutine(cloudCoroutine);
clouds.FindAll(x => x).ForEach(x => x.Kill());
StartCoroutine(DisableLoadingScreen());
}
}