summaryrefslogtreecommitdiff
path: root/Assets/Scripts/Core/Loader.cs
blob: 23cf216b31dcb547ded5d64f9680b0b98078303e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

namespace Core
{
    public class Loader : MonoBehaviour
    {
        public static Loader Current;
        
        public List<LoadGroup> loadGroups;
        public UnityEvent onLoaded;
        
        private bool _started;
        
        
#if UNITY_EDITOR
        [HideInInspector] public int objectCount;
        [HideInInspector] public int loadedObjectCount;

        private void OnGUI()
        {
            GUILayout.Label($"Loaded: {loadedObjectCount / objectCount * 100}% ({loadedObjectCount}/{objectCount})");
        }
#endif

        private void Update()
        {
            if (!_started)
                _started = true;
        }

        private void Awake()
        {
#if UNITY_EDITOR
            foreach (var loadGroup in loadGroups)
                objectCount += loadGroup.GameObjects.Count;
#endif
            if (Current == null)
                Current = this;

            StartCoroutine(Load());
        }

        private IEnumerator Load()
        {
            yield return new WaitUntil(() => _started);
            foreach (var loadGroup in loadGroups)
            {
                if (loadGroups == null)
                    continue;
                foreach (var loadGroupGameObject in loadGroup.GameObjects)
                {
                    Instantiate(loadGroupGameObject);
#if UNITY_EDITOR
                    loadedObjectCount++;
#endif
                    yield return null;
                }
            }
            onLoaded.Invoke();
            Destroy(gameObject);
        }

        private void OnDestroy()
        {
            if (Current == this)
                Current = null;
        }
    }
}