-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSettingsManager.cs
93 lines (86 loc) · 2.71 KB
/
SettingsManager.cs
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System;
using System.Collections;
using System.IO;
using Assets.Scripts.Models.Settings;
using Assets.Scripts.Utils;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
namespace Assets.Scripts.Managers
{
/// <summary>
/// This class will serve the <see cref="SettingsModel"/> across the whole application.
/// Default it is set with the default options in the models.
/// Because we focus on WebGL it is not possible to load a file directly, we actually need to load through a web request.
/// This means the config.json MUST be in the root of the web server, which is not the nicest way.
/// </summary>
internal class SettingsManager : Singleton<SettingsManager>
{
public UnityEvent SettingsLoadedEvent = new UnityEvent();
public SettingsModel Settings { get; private set; } = new SettingsModel();
public GameObject AlertCanvas;
private TMP_Text _alertText;
/// <summary>
/// Read the settings on awake state.
/// </summary>
void Start()
{
_alertText = AlertCanvas.GetComponentInChildren<TMP_Text>();
const string configFileName = "config.json";
//Read our config file. If WebGL we actually need to do a web request
if (Application.platform == RuntimePlatform.WebGLPlayer)
{
StartCoroutine(GetConfigJson());
}
else
{
try
{
StreamReader reader = new StreamReader(configFileName);
Settings = JsonUtility.FromJson<SettingsModel>(reader.ReadToEnd());
Debug.Log("Settings loaded");
SettingsLoadedEvent?.Invoke();
}
catch (ArgumentException e)
{
Debug.LogError(e.Message);
_alertText.text = $"Failed loading the configuration.\r\nInvalid configuration file.";
AlertCanvas.SetActive(true);
}
catch (FileNotFoundException e)
{
Debug.LogError(e.Message);
_alertText.text = $"Failed loading the configuration.\r\nMissing configuration file.";
AlertCanvas.SetActive(true);
}
}
}
/// <summary>
/// Load the config through a web request.
/// </summary>
/// <returns></returns>
private IEnumerator GetConfigJson()
{
using (UnityWebRequest webRequest = UnityWebRequest.Get("/config.json"))
{
// Request and wait for the desired page.
webRequest.timeout = 10;
yield return webRequest.SendWebRequest();
if (webRequest.isNetworkError || webRequest.isHttpError)
{
Debug.LogError($"Retrieving config failed");
_alertText.text = "Failed loading the configuration.\r\nMissing configuration file";
AlertCanvas.SetActive(true);
}
else
{
Settings = JsonUtility.FromJson<SettingsModel>(webRequest.downloadHandler.text);
SettingsLoadedEvent?.Invoke();
Debug.Log("Settings loaded");
}
yield return null;
}
}
}
}