Premier commit

This commit is contained in:
mrtoine 2025-10-10 18:53:01 +02:00
commit a492d86558
158 changed files with 14898 additions and 0 deletions

8
Assets/_/Features.meta Normal file
View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 4e3aa737e49e34b5d9db99c44f9fc752
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 48cfbe4e898706c4dad037e29ac2342c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e5c81e462649248b0847fb109b449032
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,55 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
namespace Core.Runtime
{
public class AudioOneShot : MonoBehaviour
{
public static void PlayAndDestroy(
AudioClip clip,
Vector3 position,
float volume = 1f,
float spatialBlend = 1f,
float pitch = 1f,
float minDistance = 1f,
float maxDistance = 20f,
AudioMixerGroup output = null)
{
if (clip == null) return;
var runner = new GameObject("AudioOneShotRunner").AddComponent<AudioOneShot>();
DontDestroyOnLoad(runner.gameObject);
runner.StartCoroutine(runner.PlayRoutine(clip, position, volume, spatialBlend, pitch, minDistance, maxDistance, output));
}
private IEnumerator PlayRoutine(AudioClip clip, Vector3 position, float volume, float spatialBlend, float pitch, float minDistance, float maxDistance, AudioMixerGroup output)
{
var go = new GameObject($"OneShot_{clip.name}");
go.transform.position = position;
var src = go.AddComponent<AudioSource>();
src.playOnAwake = false;
src.volume = volume;
src.pitch = Mathf.Max(0.01f, pitch);
src.spatialBlend = Mathf.Clamp01(spatialBlend);
src.minDistance = minDistance;
src.maxDistance = maxDistance;
src.rolloffMode = AudioRolloffMode.Logarithmic;
src.outputAudioMixerGroup = output;
// On assigne le clip et on joue
src.clip = clip;
src.Play();
// Attendre la fin réelle de la lecture
while (src != null && (src.isPlaying || src.time < clip.length))
yield return null;
if (go != null) Object.Destroy(go);
if (this != null) Object.Destroy(gameObject); // détruire le runner
}
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 403d34891ad64003a08b2d22330793c4
timeCreated: 1758098472

View file

@ -0,0 +1,138 @@
using System.Collections.Generic;
using Core.Runtime.Interfaces;
using UnityEngine;
namespace Core.Runtime
{
public class BaseMonoBehaviour : MonoBehaviour
{
#region Publics
[Header("Debug")]
[SerializeField] protected bool m_isVerbose;
public enum FactPersistence
{
Normal,
Persistent,
}
public GameObject GameObject => _gameObject ? _gameObject : _gameObject = gameObject;
public Rigidbody Rigidbody => _rigidbody ? _rigidbody : _rigidbody = GetComponent<Rigidbody>();
public Transform Transform => _transform ? _transform : _transform = GetComponent<Transform>();
#endregion
#region Fact Dictionnary
protected bool FactExists<T>(string key, out T value)
{
GameFacts.FactExists<T>(key, out value);
return value != null;
}
protected T GetFact<T>(string key)
{
return GameFacts.GetFact<T>(key);
}
protected Dictionary<string, IFact> GetAllFacts()
{
return GameFacts.GetAllFacts();
}
protected void SetFact<T>(string key, T value, FactPersistence persistence = FactPersistence.Normal)
{
GameFacts.SetFact<T>(key, value, persistence);
}
protected void RemoveFact<T>(string key)
{
GameFacts.RemoveFact<T>(key);
}
#endregion
#region Save System
protected List<string> GetAllSaves()
{
return GameFacts.GetAllSaves();
}
protected void SaveFacts(string slotName = "")
{
string slot = GameManager.Instance.Profile;
if (slotName != "")
{
slot = slotName;
}
if (GameFacts.SaveFacts(slot))
{
Info("Données sauvegardées avec succès dans le fichier save.json");
}
else
{
Error("Failed to save facts");
}
}
protected void LoadFacts(string slotName = "")
{
string slot = GameManager.Instance.Profile;
if (slotName != "")
{
slot = slotName;
}
if (GameFacts.LoadFacts(slot))
{
Info("Données chargées avec succès");
}
else
{
Error("Failed to load facts");
}
}
protected void DeleteSaveFile()
{
GameFacts.DeleteSaveFile(GameManager.Instance.Profile);
}
#endregion
#region DEBUG
protected void Info(string message)
{
if (!m_isVerbose) return;
Debug.Log(message, this);
}
protected void Error(string message)
{
if (!m_isVerbose) return;
Debug.LogError(message, this);
}
protected void Warning(string message)
{
if (!m_isVerbose) return;
Debug.LogWarning(message, this);
}
#endregion
#region GETTERS
private GameObject _gameObject;
private Rigidbody _rigidbody;
private Transform _transform;
protected FactDictionnary GameFacts => GameManager.m_gameFacts;
#endregion
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5a0991893b6c24954afe021de03614ad

View file

@ -0,0 +1,51 @@
using System;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Core.Runtime
{
public class CheckManagers : MonoBehaviour
{
#region Publics
//
#endregion
#region Unity API
void Awake()
{
if (GameManager.Instance == null)
{
SceneManager.LoadScene("TitleScreen");
}
}
#endregion
#region Main Methods
//
#endregion
#region Utils
/* Fonctions privées utiles */
#endregion
#region Privates and Protected
// Variables privées
#endregion
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 07a79fcaf2ea4d4e82777e9dec39d553
timeCreated: 1757927209

View file

@ -0,0 +1,16 @@
{
"name": "Core.Runtime",
"rootNamespace": "Core.Runtime",
"references": [
"GUID:6055be8ebefd69e48b49212b09b47b2f"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View file

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f86a85de7d85846209da708ccd7175e8
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
namespace Core.Runtime
{
public enum EnumInputs
{
Player,
UI
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b2da6a29581940dc80af532617ecda96
timeCreated: 1757927538

View file

@ -0,0 +1,9 @@
namespace Core.Runtime._.Features.Core.Runtime
{
public enum EnumLanguage
{
French,
English,
Spanish,
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: fc6a721d7edb4ea2b419513579ab9621
timeCreated: 1758878437

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 6cacc9eeddc0145c6b5621147a413323
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,43 @@
using System;
using Core.Runtime.Interfaces;
using Newtonsoft.Json;
using UnityEngine;
namespace Core.Runtime
{
public class Fact<T> : IFact
{
#region Publics
public T Value;
public Fact(object value, bool isPersistent)
{
Value = (T) value;
IsPersistent = isPersistent;
}
public Type ValueType => typeof(T);
[JsonIgnore]
public object GetObjectValue => Value;
public void SetObjectValue(object value)
{
if (value is T cast)
{
Value = cast;
}
else
{
throw new InvalidCastException("Cannot asign a value to a fact");
}
}
public bool IsPersistent { get; set; }
#endregion
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: dbdaad04e901476ebafb6f2c0d22a257
timeCreated: 1752132457

View file

@ -0,0 +1,214 @@
using System;
using System.Collections.Generic;
using System.IO;
using Core.Runtime.Interfaces;
using Newtonsoft.Json;
using UnityEngine;
namespace Core.Runtime
{
public class FactDictionnary
{
#region Publics
public Dictionary<string, IFact> AllFacts => _facts;
#endregion
#region Main Methods
public bool FactExists<T>(string key, out T value)
{
if (_facts.TryGetValue(key, out var fact) && fact is Fact<T> typedFact)
{
value = typedFact.Value;
return true;
}
value = default;
return false;
}
public void SetFact<T>(string key, T value, BaseMonoBehaviour.FactPersistence persistence)
{
if (_facts.TryGetValue(key, out var existingFact))
{
if (existingFact is Fact<T> typedFact)
{
typedFact.Value = value;
typedFact.IsPersistent = persistence == BaseMonoBehaviour.FactPersistence.Persistent;
}
else
{
throw new InvalidCastException("Fact exists but is a wrong type");
}
}
else
{
bool isPersistent = persistence == BaseMonoBehaviour.FactPersistence.Persistent;
_facts[key] = new Fact<T>(value, isPersistent);
}
}
public T GetFact<T>(string key)
{
if (!_facts.TryGetValue(key, out var fact))
{
throw new InvalidCastException($"Fact {key} does not exist");
}
if (_facts[key] is not Fact<T> typedFact)
{
throw new InvalidCastException($"Fact {key} is not of type {typeof(T)}");
}
return typedFact.Value;
}
public Dictionary<string, IFact> GetAllFacts()
{
return AllFacts;
}
public List<T> GetAllFactsOfType<T>()
{
List<T> list = new();
foreach (var fact in _facts.Values)
{
if (fact is Fact<T> typedFact)
{
list.Add(typedFact.Value);
}
}
return list;
}
public void RemoveFact<T>(string key)
{
_facts.Remove(key);
}
public List<string> GetAllSaves()
{
foreach (var slot in Directory.GetFiles(Application.persistentDataPath))
{
if (slot.Contains("_save.json") && (!slot.Contains("GeneralSettings") || !slot.Contains("continue")))
{
string fileName = Path.GetFileNameWithoutExtension(slot);
if (fileName.EndsWith("_save"))
{
string slotName = fileName.Substring(0, fileName.Length - "_save".Length); // "Rom1"
_saves.Add(slotName);
}
}
}
return _saves;
}
public bool SaveFileExists(string slotName= "")
{
if (slotName != "")
{
string filename = Path.Combine(Application.persistentDataPath, $"{slotName}_save.json");
return File.Exists(filename);
}
int nbFiles = Directory.GetFiles(Application.persistentDataPath, "*.json").Length;
string fileSettings = Path.Combine(Application.persistentDataPath, "GeneralSettings_save.json");
string fileContinue = Path.Combine(Application.persistentDataPath, "continue_save.json");
if (File.Exists(fileSettings)) nbFiles--; // On retire le fichier nommé GeneralSettings_save.json
if (File.Exists(fileContinue)) nbFiles--; // On retire le fichier nommé continue_save.json
if(nbFiles <= 0) return false;
return true;
}
public bool SaveFacts(string slotName)
{
Dictionary<string, IFact> persistentsFacts = GetPersistentsFacts();
// Permet à Newtonsoft de savoir quel type concret sérialiser via le champ $type
JsonSerializerSettings settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
TypeNameHandling = TypeNameHandling.All // Ajout du type dans le JSON
};
string json = JsonConvert.SerializeObject(persistentsFacts, settings);
string filename = Path.Combine(Application.persistentDataPath, $"{slotName}_save.json");
//Debug.Log($"Saving to {filename}");
try
{
File.WriteAllText(filename, json);
_saves.Add(slotName);
return true;
}
catch (Exception e)
{
return false;
}
}
public bool LoadFacts(string slotName)
{
string file = Path.Combine(Application.persistentDataPath, $"{slotName}_save.json");
if (File.Exists(file))
{
// Permet à Newtonsoft de savoir quel type concret désérialiser via le champ $type
JsonSerializerSettings settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
};
string json = File.ReadAllText(file);
Dictionary<string, IFact> facts = JsonConvert.DeserializeObject<Dictionary<string, IFact>>(json, settings);
foreach (var fact in facts)
{
_facts[fact.Key] = fact.Value;
}
return true;
}
return false;
}
public void DeleteSaveFile(string slotName)
{
string file = Path.Combine(Application.persistentDataPath, $"{slotName}_save.json");
File.Delete(file);
}
#endregion
#region Utils
private Dictionary<string, IFact> GetPersistentsFacts()
{
Dictionary<string, IFact> persistentsFacts = new();
foreach (var fact in _facts)
{
if (fact.Value.IsPersistent)
{
persistentsFacts.Add(fact.Key, fact.Value);
}
}
return persistentsFacts;
}
#endregion
#region private
private Dictionary<string, IFact> _facts = new();
private List<string> _saves = new List<string>();
#endregion
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: bb7f99aca4b5495aaecca229e21225ef
timeCreated: 1752132416

View file

@ -0,0 +1,295 @@
using System;
using System.Collections.Generic;
using Core.Runtime._.Features.Core.Runtime;
using Core.Runtime.Interfaces;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Core.Runtime
{
[RequireComponent(typeof(SceneLoader), typeof(LocalizationSystem))]
public class GameManager: BaseMonoBehaviour
{
#region Publics
public static GameManager Instance { get; set; }
public static FactDictionnary m_gameFacts;
public static event Action<bool> OnMenuCalled;
public static event Action OnKonamiCode;
public bool IsOnPause
{
get => isOnPause;
set => isOnPause = value;
}
public FactDictionnary Fact
{
get
{
return _fact;
}
set
{
_fact = value;
}
}
public String Profile
{
get
{
return _profile;
}
set
{
_profile = value;
}
}
public bool SaveFileExist => m_gameFacts.SaveFileExists();
public bool CanPause
{
get => _canPause;
set => _canPause = value;
}
public EnumLanguage CurrentLanguage
{
get
{
return _currentLanguage;
}
set
{
_currentLanguage = value;
}
}
public Dictionary<string, string> GetLocalTexts
{
get
{
return _localTexts;
}
set
{
_localTexts = value;
}
}
public string CurrentSceneName
{
get
{
return _currentSceneName;
}
set
{
_currentSceneName = value;
}
}
public string SecondSceneName
{
get
{
return _secondSceneName;
}
set
{
_secondSceneName = value;
}
}
#endregion
#region Unity API
void Awake()
{
_sceneLoader = GetComponent<SceneLoader>();
// Si une instance existe déjà et que ce nest pas celle-ci, détruire ce GameObject
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
// Sinon, cette instance devient linstance unique
Instance = this;
DontDestroyOnLoad(gameObject);
m_gameFacts = new FactDictionnary();
_localTexts = new Dictionary<string, string>();
if (m_gameFacts.SaveFileExists("GeneralSettings"))
{
LoadFacts("GeneralSettings");
}
else
{
GeneralSettings settings = new GeneralSettings
{
Language = EnumLanguage.French,
GeneralVolume = 1,
MusicVolume = 1,
MetronomeVolume = 1,
SfxVolume = 1
};
SetFact<GeneralSettings>("GeneralSettings", settings, FactPersistence.Persistent);
SaveFacts("GeneralSettings");
}
CurrentLanguage = GetFact<GeneralSettings>("GeneralSettings").Language;
LocalizationSystem.Instance.LoadLanguage(CurrentLanguage);
}
void Update()
{
CheckKonamiCode();
if(SceneManager.GetActiveScene().name == "TitleScreen") return;
if (!CanPause) return;
if (Input.GetKeyDown(KeyCode.Escape) && CanPause)
{
IsOnPause = !IsOnPause;
OnMenuCalled?.Invoke(IsOnPause);
}
if (IsOnPause && CanPause)
{
SetInputs(EnumInputs.UI);
}
else
{
OnMenuCalled?.Invoke(IsOnPause);
SetInputs(EnumInputs.Player);
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
}
#endregion
#region Main Methods
public void RegisterInputHandler(IInputHandler handler)
{
_inputHandler = handler;
}
public void SetInputs(EnumInputs value)
{
switch (value)
{
case EnumInputs.UI:
_inputHandler?.EnableUI();
break;
case EnumInputs.Player:
_inputHandler?.EnablePlayer();
break;
}
}
public void CreateObject(GameObject prefab, Vector3 position)
{
Instantiate(prefab, position, Quaternion.identity);
}
public void ReloadScene()
{
string sceneName = SceneManager.GetActiveScene().name;
_sceneLoader.LoadScene(sceneName);
}
#endregion
#region Utils
/* Fonctions privées utiles */
void CheckKonamiCode()
{
if (_konamiIndex > 0)
{
_konamiTimer += Time.deltaTime;
if (_konamiTimer >= _konamiStepTimeout)
{
_konamiTimer = 0f;
_konamiIndex = 0;
}
}
if (Input.anyKeyDown)
{
if (Input.GetKeyDown(_konamiSequence[_konamiIndex]))
{
_konamiIndex++;
_konamiTimer = 0f;
if (_konamiIndex >= _konamiSequence.Length)
{
_konamiIndex = 0;
_konamiTimer = 0f;
TriggerKonamiEsaterEgg();
}
}
else
{
_konamiIndex = 0;
_konamiTimer = 0f;
}
}
}
void TriggerKonamiEsaterEgg()
{
_myClip = Resources.Load<AudioClip>("Audio/harp-flourish-6251");
_someWorldPos = new Vector3(0, 0, 0);
AudioOneShot.PlayAndDestroy(_myClip, _someWorldPos, 1f, spatialBlend: 1f);
OnKonamiCode?.Invoke();
}
#endregion
#region Privates and Protected
bool isOnPause = false;
SceneLoader _sceneLoader;
FactDictionnary _fact;
bool _canPause;
string _profile;
EnumLanguage _currentLanguage = EnumLanguage.French;
Dictionary<string, string> _localTexts;
static IInputHandler _inputHandler;
int _konamiIndex = 0;
float _konamiTimer = 0f;
float _konamiStepTimeout = 1f;
readonly KeyCode[] _konamiSequence = new[]
{
KeyCode.UpArrow, KeyCode.UpArrow,
KeyCode.DownArrow, KeyCode.DownArrow,
KeyCode.LeftArrow, KeyCode.RightArrow,
KeyCode.LeftArrow, KeyCode.RightArrow,
KeyCode.B, KeyCode.Q
};
AudioClip _myClip;
Vector3 _someWorldPos;
string _currentSceneName;
string _secondSceneName;
#endregion
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3664fb5e6bffa4a6cbfc8fce31b53be3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 11
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,60 @@
using System.Collections.Generic;
using Core.Runtime._.Features.Core.Runtime;
namespace Core.Runtime
{
public class GeneralSettings
{
#region Attributes
EnumLanguage _language;
float _generalVolume;
float _musicVolume;
private float _metronomeVolume;
float _sfxVolume;
#endregion
#region Getters and Setters
public EnumLanguage Language
{
get => _language;
set => _language = value;
}
public float GeneralVolume
{
get => _generalVolume;
set => _generalVolume = value;
}
public float MusicVolume
{
get => _musicVolume;
set => _musicVolume = value;
}
public float MetronomeVolume
{
get => _metronomeVolume;
set => _metronomeVolume = value;
}
public float SfxVolume
{
get => _sfxVolume;
set => _sfxVolume = value;
}
#endregion
public List<int> ApplyResolution(string resolution)
{
string[] res = resolution.Split('x');
return new List<int> { int.Parse(res[0]), int.Parse(res[1]) };
}
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 93e49b753dd642e3bb11f51adfb2fdf8
timeCreated: 1754912382

View file

@ -0,0 +1,21 @@
using UnityEngine;
namespace Core.Runtime._.Features.Core.Runtime
{
public class GlobalEventSystem : MonoBehaviour
{
private static GlobalEventSystem _instance;
private void Awake()
{
if (_instance != null)
{
Destroy(gameObject); // Détruire les doublons
return;
}
_instance = this;
DontDestroyOnLoad(gameObject); // Rendre persistant
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 926d511d0daac3c40a9c01ec1f8190c0

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d65176b4369414721beed3a163bf9929
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,7 @@
namespace Core.Runtime.Interfaces
{
public interface IEvent
{
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d7d3d7aa6d7c42d1b37d418d570a6489
timeCreated: 1758027691

View file

@ -0,0 +1,12 @@
using System;
namespace Core.Runtime.Interfaces
{
public interface IFact
{
Type ValueType { get; }
object GetObjectValue { get; }
void SetObjectValue(object value);
bool IsPersistent { get; }
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 28d823c3a267436eaf00bf170c9669f9
timeCreated: 1752132484

View file

@ -0,0 +1,8 @@
namespace Core.Runtime.Interfaces
{
public interface IInputHandler
{
void EnablePlayer();
void EnableUI();
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 343bec88c3a642b6acebd80f8cefe8e3
timeCreated: 1757928664

View file

@ -0,0 +1,41 @@
using System;
using System.Collections;
using DG.Tweening;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Core.Runtime
{
public class LoadingScene : BaseMonoBehaviour
{
private void Awake()
{
SceneLoader.Instance.LoadSceneAsync(GameManager.Instance.CurrentSceneName);
if(GameManager.Instance.SecondSceneName != null)
{
DOTween.KillAll();
SceneLoader.Instance.LoadSceneBackground(GameManager.Instance.SecondSceneName);
}
}
private void Start()
{
LocalizationSystem.Instance.LocalizeAllTextsIn(transform);
}
private void Update()
{
if (SceneLoader.Instance.IsLoading)
{
float progress = SceneLoader.Instance.Progress;
if (_progressNum != null)
{
_progressNum.text = $"{progress * 100:00}%";
}
}
}
[SerializeField] TMP_Text _progressNum;
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: be958fd84cb8466f94bf41a8a6645077
timeCreated: 1758699294

View file

@ -0,0 +1,110 @@
using System;
using System.Collections.Generic;
using System.IO;
using Core.Runtime._.Features.Core.Runtime;
using TMPro;
using UnityEngine;
namespace Core.Runtime
{
public class LocalizationSystem : BaseMonoBehaviour
{
#region Publics
public static LocalizationSystem Instance { get; private set; }
#endregion
#region Unity API
private void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
}
#endregion
#region Main Methods
public void LocalizeAllTextsIn(Transform root)
{
foreach (var txt in root.GetComponentsInChildren<TMP_Text>(true))
{
txt.text = GetLocalizedText(txt.text);
}
}
/*public string GetLocalizedText(string key)
{
if (GameManager.Instance.GetLocalTexts.TryGetValue(key, out var value))
return value;
return $"{key}";
}*/
public string GetLocalizedText(string key)
{
if (GameManager.Instance.GetLocalTexts.TryGetValue(key, out var value))
return value;
return key;
}
public void SaveLanguage(string newLanguage)
{
//
}
public void LoadLanguage(EnumLanguage langReceived)
{
string lang = langReceived.ToString();
if (Enum.TryParse(lang, out EnumLanguage parsedLang))
{
GameManager.Instance.GetLocalTexts = XmlLoader.LoadDictionary(GetLanguageFile(langReceived));
}
else
{
Debug.LogError($"[ERROR] La langue '{lang}' ne correspond pas à un membre de EnumLanguage.");
return; // Si la conversion échoue, on sort de la méthode
}
}
#endregion
#region Utils
private string GetLanguage()
{
string file = GetLanguageFile();
return file.Split('/')[file.Split('/').Length - 1].Split('.')[0];
}
private string GetLanguageFile(EnumLanguage lang = EnumLanguage.French)
{
//string filename = Application.dataPath + "/_/Database/Localization/" + GetFact<GeneralSettings>("GeneralSettings").Language + ".xml";
string filename = $"Localization/{lang}.xml";
string filepath = Path.Combine(Application.streamingAssetsPath, filename);
if (File.Exists(filepath))
{
return filepath;
}
return Path.Combine(Application.streamingAssetsPath, "French.xml");
}
#endregion
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 02c5410883674e91875167d2ef34abe5
timeCreated: 1752475493

View file

@ -0,0 +1,166 @@
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
using Random = UnityEngine.Random;
namespace Core.Runtime
{
public class SceneLoader : BaseMonoBehaviour
{
#region Publics
public static event Action<Scene> OnSceneLoaded;
public static string CurrentSceneName => SceneManager.GetActiveScene().name;
public static SceneLoader Instance { get; private set; }
public float Progress => _progress;
public bool IsLoading => _progress < 1f;
#endregion
#region Unity API
private void Awake()
{
if (Instance != null)
{
Destroy(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
SceneManager.sceneLoaded += HandleSceneLoaded;
}
void OnDestroy()
{
SceneManager.sceneLoaded -= HandleSceneLoaded;
}
#endregion
#region Main Methods
public void LoadScene(string sceneName)
{
SceneManager.LoadScene(sceneName);
}
public void LoadSceneAsync(string sceneName)
{
StartCoroutine(LoadSceneWithAsync(sceneName));
}
public void LoadSceneBackground(string sceneName)
{
SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive).completed += (operation) =>
{
SetSceneActive(sceneName, false);
};
}
public void SetSceneActive(string sceneName, bool isActive)
{
Scene scene = SceneManager.GetSceneByName(sceneName);
if (scene.IsValid() && scene.isLoaded)
{
foreach (GameObject rootObj in scene.GetRootGameObjects())
{
rootObj.SetActive(isActive);
}
}
else
{
Debug.Log($"<color=red>La scène {sceneName} n'est pas chargée ou invalide.</color>");
}
}
public void UnloadScene(string sceneName)
{
if (SceneManager.GetSceneByName(sceneName).isLoaded)
{
SceneManager.UnloadSceneAsync(sceneName).completed += (operation) =>
{
return;
};
}
}
public void FakeLoading(string nextSceneName)
{
Info("On vérifie que la scene Loading est disponible");
if (SceneExists("Loading"))
{
LoadScene("Loading");
Info($"level suivant {nextSceneName}");
StartCoroutine(WaitingLoading(nextSceneName));
}
}
#endregion
#region Utils
private IEnumerator LoadSceneWithAsync(string sceneName)
{
AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(sceneName);
asyncOperation.allowSceneActivation = false;
while (!asyncOperation.isDone)
{
_progress = Mathf.Clamp01(asyncOperation.progress / .9f);
if (asyncOperation.progress >= .9f)
{
yield return new WaitForSeconds(1);
asyncOperation.allowSceneActivation = true;
}
yield return null;
_progress = 1f;
}
}
private IEnumerator WaitingLoading(string nextSceneName)
{
int time = Random.Range(3, 6);
Info($"On attend {time} secondes et on charge la scene {nextSceneName}");
yield return new WaitForSeconds(time);
LoadScene(nextSceneName);
}
private void HandleSceneLoaded(Scene scene, LoadSceneMode mode)
{
OnSceneLoaded?.Invoke(scene);
}
private bool SceneExists(string sceneName)
{
for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++)
{
string path = SceneUtility.GetScenePathByBuildIndex(i);
string name = System.IO.Path.GetFileNameWithoutExtension(path);
if (name == sceneName)
return true;
}
return false;
}
#endregion
#region Privates and Protected
float _progress;
#endregion
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 9a4bd386e20d414fb3e91c510e890143
timeCreated: 1751130958

View file

@ -0,0 +1,19 @@
using UnityEngine;
namespace Core.Runtime
{
public class TranslationTextTransfform : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
private void Start()
{
LocalizationSystem.Instance.LocalizeAllTextsIn(transform);
}
// Update is called once per frame
void Update()
{
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 56005dfbf2859e9478184b0345121367

View file

@ -0,0 +1,22 @@
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using UnityEngine;
namespace Core.Runtime
{
public class XmlLoader
{
public static Dictionary<string, string> LoadDictionary(string filepath)
{
XDocument xmlDoc = XDocument.Load(filepath);
return xmlDoc.Root
.Elements()
.ToDictionary(
e => e.Name.LocalName,
e => e.Value
);
}
}
}

View file

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f0170f390842426a826731a88149968e
timeCreated: 1752483882