diff --git a/AutoSceneChanger.cs b/AutoSceneChanger.cs index c7b60ea..416df6f 100644 --- a/AutoSceneChanger.cs +++ b/AutoSceneChanger.cs @@ -1,5 +1,4 @@ using UnityEngine; -using UnityEngine.SceneManagement; namespace NEG.Utils { @@ -9,5 +8,4 @@ namespace NEG.Utils private void Start() => SceneManager.LoadScene(1); #endif } -} - +} \ No newline at end of file diff --git a/Collections/DictionaryExtensions.cs b/Collections/DictionaryExtensions.cs index aae8985..ea5d2d7 100644 --- a/Collections/DictionaryExtensions.cs +++ b/Collections/DictionaryExtensions.cs @@ -5,7 +5,8 @@ namespace NEG.Utils.Collections public static class DictionaryExtensions { /// - /// Adds given value to a dictionary if there was no element at given , replaces element with otherwise. + /// Adds given value to a dictionary if there was no element at given , replaces element with + /// otherwise. /// /// true if element was added, false if it was replaced public static bool AddOrUpdate(this Dictionary dict, K key, V value) @@ -15,27 +16,23 @@ namespace NEG.Utils.Collections dict[key] = value; return false; } - else - { - dict.Add(key, value); - return true; - } + + dict.Add(key, value); + return true; } /// - /// Gets a value from the dictionary under a specified key or adds it if did not exist and returns . + /// Gets a value from the dictionary under a specified key or adds it if did not exist and returns + /// . /// - /// value under a given if it exists, otherwise + /// value under a given if it exists, otherwise public static V GetOrSetToDefault(this Dictionary dict, K key, V defaultValue) { - if (dict.TryGetValue(key, out V value)) - { - return value; - } + if (dict.TryGetValue(key, out var value)) return value; dict.Add(key, defaultValue); return defaultValue; } } -} +} \ No newline at end of file diff --git a/CoroutineUtils.cs b/CoroutineUtils.cs index a91c31c..1bf85ff 100644 --- a/CoroutineUtils.cs +++ b/CoroutineUtils.cs @@ -6,41 +6,42 @@ namespace NEG.Utils { public static class CoroutineUtils { - private static readonly WaitForEndOfFrame WaitForEndOfFrame = new WaitForEndOfFrame(); + private static readonly WaitForEndOfFrame WaitForEndOfFrame = new(); public static IEnumerator WaitForFrames(int count) { - for (int i = 0; i < count; i++) - { - yield return null; - } + for (int i = 0; i < count; i++) yield return null; } - public static void ActionAfterFrames(this MonoBehaviour mono, int count, Action action) - { + public static void ActionAfterFrames(this MonoBehaviour mono, int count, Action action) => mono.StartCoroutine(ActionAfterFrames(count, action)); - } - + public static IEnumerator ActionAfterFrames(int count, Action action) { yield return WaitForFrames(count); action?.Invoke(); } - - public static void ActionAfterEndOfFrame(this MonoBehaviour mono, Action action) => mono.StartCoroutine(ActionAtNextFrame(action)); + + public static void ActionAfterEndOfFrame(this MonoBehaviour mono, Action action) => + mono.StartCoroutine(ActionAtNextFrame(action)); + public static IEnumerator ActionAfterEndOfFrame(Action action) { yield return WaitForEndOfFrame; action?.Invoke(); } - public static void ActionAtNextFrame(this MonoBehaviour mono, Action action) => mono.StartCoroutine(ActionAtNextFrame(action)); + + public static void ActionAtNextFrame(this MonoBehaviour mono, Action action) => + mono.StartCoroutine(ActionAtNextFrame(action)); + public static IEnumerator ActionAtNextFrame(Action action) { yield return null; action?.Invoke(); } - public static void ActionAfterTime(this MonoBehaviour mono, float time, Action action) => mono.StartCoroutine(ActionAfterTime(time, action)); + public static void ActionAfterTime(this MonoBehaviour mono, float time, Action action) => + mono.StartCoroutine(ActionAfterTime(time, action)); public static IEnumerator ActionAfterTime(float time, Action action) { diff --git a/Editor/BuildingUtils.cs b/Editor/BuildingUtils.cs index a95774f..cd507f2 100644 --- a/Editor/BuildingUtils.cs +++ b/Editor/BuildingUtils.cs @@ -1,8 +1,8 @@ using System.Diagnostics; using System.Linq; -using UnityEngine; using UnityEditor; -using UnityEditor.Build.Player; +using UnityEditor.Build; +using UnityEngine; using Debug = UnityEngine.Debug; public static class BuildingUtils @@ -12,32 +12,32 @@ public static class BuildingUtils [MenuItem("Tools/PrepareForBuild", priority = -10)] public static void PrepareForBuild() { - var namedBuildTarget = UnityEditor.Build.NamedBuildTarget.FromBuildTargetGroup( + var namedBuildTarget = NamedBuildTarget.FromBuildTargetGroup( BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget)); - var args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget); + string[] args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget); var argsList = args.ToList(); argsList.Remove(SteamBuildDefine); PlayerSettings.SetScriptingDefineSymbols(namedBuildTarget, argsList.ToArray()); } - + [MenuItem("Tools/PlatformDefines/Steam", priority = -1)] public static void SetDefinesForSteam() { PrepareForBuild(); - - var namedBuildTarget = UnityEditor.Build.NamedBuildTarget.FromBuildTargetGroup( + + var namedBuildTarget = NamedBuildTarget.FromBuildTargetGroup( BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget)); - var args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget); + string[] args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget); var argsList = args.ToList(); argsList.Add(SteamBuildDefine); PlayerSettings.SetScriptingDefineSymbols(namedBuildTarget, argsList.ToArray()); } - - + + [MenuItem("Tools/Build/Steam/Release")] public static void SteamRelease() { - if(!CanBuild()) + if (!CanBuild()) return; IncreaseBuildNumber(); @@ -48,21 +48,21 @@ public static class BuildingUtils [MenuItem("Tools/Build/Steam/Development")] public static void SteamDevelopment() { - if(!CanBuild()) + if (!CanBuild()) return; - + IncreaseBuildNumber(); BuildDevelopment(); UploadSteam(); } - - + + [MenuItem("Tools/Build/Steam/Demo")] public static void SteamDemo() { - if(!CanBuild()) + if (!CanBuild()) return; - + IncreaseBuildNumber(); BuildDemo(); UploadSteam(true); @@ -71,7 +71,7 @@ public static class BuildingUtils [MenuItem("Tools/Build/All Release")] public static void BuildRelease() { - if(!CanBuild()) + if (!CanBuild()) return; BuildWindowsRelease(); BuildLinuxRelease(); @@ -80,24 +80,24 @@ public static class BuildingUtils [MenuItem("Tools/Build/All Development")] public static void BuildDevelopment() { - if(!CanBuild()) + if (!CanBuild()) return; BuildWindowsDevelopment(); } - + [MenuItem("Tools/Build/All Demo")] public static void BuildDemo() { - if(!CanBuild()) + if (!CanBuild()) return; - BuildWindows(true, new[] {"DEMO"}); - BuildLinux(true, new[] {"DEMO"}); + BuildWindows(true, new[] { "DEMO" }); + BuildLinux(true, new[] { "DEMO" }); } [MenuItem("Tools/Build/Platform/Windows/x64-Development")] public static void BuildWindowsDevelopment() { - if(!CanBuild()) + if (!CanBuild()) return; BuildWindows(false); } @@ -105,19 +105,19 @@ public static class BuildingUtils [MenuItem("Tools/Build/Platform/Windows/x64-Release")] public static void BuildWindowsRelease() { - if(!CanBuild()) + if (!CanBuild()) return; BuildWindows(true); } - + [MenuItem("Tools/Build/Platform/Linux/x64-Release")] public static void BuildLinuxRelease() { - if(!CanBuild()) + if (!CanBuild()) return; BuildLinux(true); } - + [MenuItem("Tools/Build/Platform/Android/GooglePlay")] public static void BuildGooglePlay() @@ -125,13 +125,11 @@ public static class BuildingUtils IncreaseBuildNumber(); PlayerSettings.Android.bundleVersionCode++; EditorUserBuildSettings.buildAppBundle = true; - + var buildPlayerOptions = new BuildPlayerOptions { scenes = new string[EditorBuildSettings.scenes.Length] }; for (int i = 0; i < EditorBuildSettings.scenes.Length; i++) - { buildPlayerOptions.scenes[i] = EditorBuildSettings.scenes[i].path; - } - + buildPlayerOptions.target = BuildTarget.Android; buildPlayerOptions.options = BuildOptions.None; buildPlayerOptions.locationPathName = Application.dataPath + @@ -143,9 +141,7 @@ public static class BuildingUtils { var buildPlayerOptions = new BuildPlayerOptions { scenes = new string[EditorBuildSettings.scenes.Length] }; for (int i = 0; i < EditorBuildSettings.scenes.Length; i++) - { buildPlayerOptions.scenes[i] = EditorBuildSettings.scenes[i].path; - } buildPlayerOptions.extraScriptingDefines = additionalDefines; @@ -155,14 +151,12 @@ public static class BuildingUtils $"/../../{Application.productName}-Steam/ContentBuilder/content/windows/{Application.productName}.exe"; BuildPipeline.BuildPlayer(buildPlayerOptions); } - + private static void BuildLinux(bool release, string[] additionalDefines = default) { var buildPlayerOptions = new BuildPlayerOptions { scenes = new string[EditorBuildSettings.scenes.Length] }; for (int i = 0; i < EditorBuildSettings.scenes.Length; i++) - { buildPlayerOptions.scenes[i] = EditorBuildSettings.scenes[i].path; - } buildPlayerOptions.extraScriptingDefines = additionalDefines; @@ -175,28 +169,29 @@ public static class BuildingUtils private static void IncreaseBuildNumber() { - string[] versionParts = PlayerSettings.bundleVersion.Split('.'); - if (versionParts.Length != 3 || !int.TryParse(versionParts[2], out int version)) { + string[] versionParts = PlayerSettings.bundleVersion.Split('.'); + if (versionParts.Length != 3 || !int.TryParse(versionParts[2], out int version)) + { Debug.LogError("IncreaseBuildNumber failed to update version " + PlayerSettings.bundleVersion); return; } + versionParts[2] = (version + 1).ToString(); PlayerSettings.bundleVersion = string.Join(".", versionParts); } private static void UploadSteam(bool demo = false) { - string command = $"cd {Application.dataPath}/../../{Application.productName}-Steam/ContentBuilder && push_build.bat"; + string command = + $"cd {Application.dataPath}/../../{Application.productName}-Steam/ContentBuilder && push_build.bat"; if (demo) - { - command = $"cd {Application.dataPath}/../../{Application.productName}-Steam/ContentBuilder && push_demo.bat"; - } + command = + $"cd {Application.dataPath}/../../{Application.productName}-Steam/ContentBuilder && push_demo.bat"; var processInfo = new ProcessStartInfo("cmd.exe", $"/c {command}") - { - CreateNoWindow = true, - UseShellExecute = false - }; + { + CreateNoWindow = true, UseShellExecute = false + }; var process = Process.Start(processInfo); process.WaitForExit(); Debug.Log(process.ExitCode); @@ -207,17 +202,18 @@ public static class BuildingUtils { if (CanBuildUtil()) return true; - Debug.LogError("Cannot build with defines set in project, please use PrepareForBuild and wait for scripts recompilation"); + Debug.LogError( + "Cannot build with defines set in project, please use PrepareForBuild and wait for scripts recompilation"); return false; } private static bool CanBuildUtil() { - var namedBuildTarget = UnityEditor.Build.NamedBuildTarget.FromBuildTargetGroup( + var namedBuildTarget = NamedBuildTarget.FromBuildTargetGroup( BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget)); - var args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget); + string[] args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget); var argsList = args.ToList(); - + if (argsList.Contains(SteamBuildDefine)) return false; diff --git a/Editor/ComponentsAdditionalItems/CanvasScalerDefault.cs b/Editor/ComponentsAdditionalItems/CanvasScalerDefault.cs index a6cb782..a459bab 100644 --- a/Editor/ComponentsAdditionalItems/CanvasScalerDefault.cs +++ b/Editor/ComponentsAdditionalItems/CanvasScalerDefault.cs @@ -8,14 +8,19 @@ namespace NEG.Utils.Editor.ComponentsAdditionalItems { [MenuItem("CONTEXT/CanvasScaler/Full HD horizontal", false, 2000)] public static void SetFullHdHorizontal(MenuCommand command) => SetComponent(command, 1920, 1080); + [MenuItem("CONTEXT/CanvasScaler/Full HD vertical", false, 2000)] public static void SetFullHdVertical(MenuCommand command) => SetComponent(command, 1080, 1920); + [MenuItem("CONTEXT/CanvasScaler/Full 2k horizontal", false, 2000)] - public static void Set2KHorizontal(MenuCommand command) => SetComponent(command, 2560, 1440 ); + public static void Set2KHorizontal(MenuCommand command) => SetComponent(command, 2560, 1440); + [MenuItem("CONTEXT/CanvasScaler/Full 2k vertical", false, 2000)] public static void Set2KVertical(MenuCommand command) => SetComponent(command, 1440, 2560); + [MenuItem("CONTEXT/CanvasScaler/Full 4k horizontal", false, 2000)] public static void Set4KHorizontal(MenuCommand command) => SetComponent(command, 3840, 2160); + [MenuItem("CONTEXT/CanvasScaler/Full 4k vertical", false, 2000)] public static void Set4KVertical(MenuCommand command) => SetComponent(command, 2160, 3840); diff --git a/Editor/EditorMultipleInstances/Editor/EditorInstanceCreator.cs b/Editor/EditorMultipleInstances/Editor/EditorInstanceCreator.cs index a24a86c..53ff6a4 100644 --- a/Editor/EditorMultipleInstances/Editor/EditorInstanceCreator.cs +++ b/Editor/EditorMultipleInstances/Editor/EditorInstanceCreator.cs @@ -11,61 +11,57 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + using System.Collections.Generic; +using System.Diagnostics; using System.IO; -using UnityEngine; using UnityEditor; +using UnityEngine; +using Debug = UnityEngine.Debug; namespace TheGamedevGuru { public class EditorInstanceCreator : EditorWindow { - string _projectInstanceName; - string _extraSubdirectories; - bool _includeProjectSettings = true; + private string _extraSubdirectories; + private bool _includeProjectSettings = true; + private string _projectInstanceName; - [MenuItem("Window/The Gamedev Guru/Editor Instance Creator")] - static void Init() - { - ((EditorInstanceCreator)EditorWindow.GetWindow(typeof(EditorInstanceCreator))).Show(); - } - - void OnGUI() + private void OnGUI() { if (string.IsNullOrEmpty(_projectInstanceName)) - { _projectInstanceName = PlayerSettings.productName + "_Slave_1"; - } - + EditorGUILayout.Separator(); EditorGUILayout.LabelField("The Gamedev Guru - Project Instance Creator"); EditorGUILayout.Separator(); EditorGUILayout.LabelField("Slave Project Name"); _projectInstanceName = EditorGUILayout.TextField("", _projectInstanceName); EditorGUILayout.Separator(); - + EditorGUILayout.LabelField("Include Project Settings? (Recommended)"); _includeProjectSettings = EditorGUILayout.Toggle("", _includeProjectSettings); EditorGUILayout.Separator(); - + EditorGUILayout.LabelField("Extra Subdirectories? (Separate by comma)"); _extraSubdirectories = EditorGUILayout.TextField("", _extraSubdirectories); EditorGUILayout.Separator(); if (GUILayout.Button("Create")) - { CreateProjectInstance(_projectInstanceName, _includeProjectSettings, _extraSubdirectories); - } - + if (GUILayout.Button("Help")) - { Application.OpenURL("https://thegamedev.guru/multiple-unity-editor-instances-within-a-single-project/"); - } } - static void CreateProjectInstance(string projectInstanceName, bool includeProjectSettings, string extraSubdirectories) + [MenuItem("Window/The Gamedev Guru/Editor Instance Creator")] + private static void Init() => ((EditorInstanceCreator)GetWindow(typeof(EditorInstanceCreator))).Show(); + + private static void CreateProjectInstance(string projectInstanceName, bool includeProjectSettings, + string extraSubdirectories) { - var targetDirectory = Path.Combine(Directory.GetCurrentDirectory(), ".." + Path.DirectorySeparatorChar, projectInstanceName); + string targetDirectory = Path.Combine(Directory.GetCurrentDirectory(), ".." + Path.DirectorySeparatorChar, + projectInstanceName); Debug.Log(targetDirectory); if (Directory.Exists(targetDirectory)) { @@ -75,29 +71,21 @@ namespace TheGamedevGuru Directory.CreateDirectory(targetDirectory); - List subdirectories = new List{"Assets", "Packages"}; - if (includeProjectSettings) - { - subdirectories.Add("ProjectSettings"); - } + var subdirectories = new List { "Assets", "Packages" }; + if (includeProjectSettings) subdirectories.Add("ProjectSettings"); - foreach (var extraSubdirectory in extraSubdirectories.Split(',')) - { + foreach (string extraSubdirectory in extraSubdirectories.Split(',')) subdirectories.Add(extraSubdirectory.Trim()); - } - foreach (var subdirectory in subdirectories) - { - System.Diagnostics.Process.Start("CMD.exe",GetLinkCommand(subdirectory, targetDirectory)); - } + foreach (string subdirectory in subdirectories) + Process.Start("CMD.exe", GetLinkCommand(subdirectory, targetDirectory)); EditorUtility.RevealInFinder(targetDirectory + Path.DirectorySeparatorChar + "Assets"); - EditorUtility.DisplayDialog("Done!", $"Done! Feel free to add it as an existing project at: {targetDirectory}", "Ok :)"); + EditorUtility.DisplayDialog("Done!", + $"Done! Feel free to add it as an existing project at: {targetDirectory}", "Ok :)"); } - static string GetLinkCommand(string subdirectory, string targetDirectory) - { - return $"/c mklink /J \"{targetDirectory}{Path.DirectorySeparatorChar}{subdirectory}\" \"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}{subdirectory}\""; - } + private static string GetLinkCommand(string subdirectory, string targetDirectory) => + $"/c mklink /J \"{targetDirectory}{Path.DirectorySeparatorChar}{subdirectory}\" \"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}{subdirectory}\""; } -} +} \ No newline at end of file diff --git a/Editor/EditorUtils.cs b/Editor/EditorUtils.cs index 9300f6d..55eeb55 100644 --- a/Editor/EditorUtils.cs +++ b/Editor/EditorUtils.cs @@ -9,7 +9,18 @@ namespace NegUtils.Editor public class AssetPath { - public string Path + private readonly string filter; + + private string path; + + + public AssetPath(string filter) + { + this.filter = filter; + TryFindPath(); + } + + public string Path { get { @@ -20,16 +31,6 @@ namespace NegUtils.Editor } } - private string path; - private readonly string filter; - - - public AssetPath(string filter) - { - this.filter = filter; - TryFindPath(); - } - private void TryFindPath() { string[] candidates = AssetDatabase.FindAssets(filter); diff --git a/Editor/GUIDToAssetPath.cs b/Editor/GUIDToAssetPath.cs index f4e5aae..4dabd33 100644 --- a/Editor/GUIDToAssetPath.cs +++ b/Editor/GUIDToAssetPath.cs @@ -1,23 +1,18 @@ using UnityEditor; using UnityEngine; - + public class GUIDToAssetPath : EditorWindow { - string guid = ""; - string path = ""; - [MenuItem("Tools/GUIDToAssetPath")] - static void CreateWindow() - { - GUIDToAssetPath window = (GUIDToAssetPath)EditorWindow.GetWindowWithRect(typeof(GUIDToAssetPath), new Rect(0, 0, 400, 120)); - } - - void OnGUI() + private string guid = ""; + private string path = ""; + + private void OnGUI() { GUILayout.Label("Enter guid"); guid = GUILayout.TextField(guid); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); - if (GUILayout.Button("Get Asset Path",GUILayout.Width(120))) + if (GUILayout.Button("Get Asset Path", GUILayout.Width(120))) path = GetAssetPath(guid); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); @@ -29,10 +24,17 @@ public class GUIDToAssetPath : EditorWindow GUILayout.EndHorizontal(); GUILayout.Label(path); } - static string GetAssetPath(string guid) + + [MenuItem("Tools/GUIDToAssetPath")] + private static void CreateWindow() + { + var window = (GUIDToAssetPath)GetWindowWithRect(typeof(GUIDToAssetPath), new Rect(0, 0, 400, 120)); + } + + private static string GetAssetPath(string guid) { guid = guid.Replace("-", ""); - + string p = AssetDatabase.GUIDToAssetPath(guid); Debug.Log(p); if (p.Length == 0) p = "not found"; diff --git a/Editor/MonoBehaviourExtensions.cs b/Editor/MonoBehaviourExtensions.cs index fb4464d..0e52560 100644 --- a/Editor/MonoBehaviourExtensions.cs +++ b/Editor/MonoBehaviourExtensions.cs @@ -1,6 +1,6 @@ using System.IO; -using UnityEngine; using UnityEditor; +using UnityEngine; namespace NEG.Utils.Editor { @@ -9,33 +9,33 @@ namespace NEG.Utils.Editor [MenuItem("CONTEXT/MonoBehaviour/Change Script")] public static void ChangeScript(MenuCommand command) { - if (command.context == null) + if (command.context == null) return; - + var monoBehaviour = command.context as MonoBehaviour; var monoScript = MonoScript.FromMonoBehaviour(monoBehaviour); - + string scriptPath = AssetDatabase.GetAssetPath(monoScript); string directoryPath = new FileInfo(scriptPath).Directory?.FullName; - + // Allow the user to select which script to replace with string newScriptPath = EditorUtility.OpenFilePanel("Select replacement script", directoryPath, "cs"); - + // Don't log anything if they cancelled the window if (string.IsNullOrEmpty(newScriptPath)) return; // Load the selected asset string relativePath = "Assets\\" + Path.GetRelativePath(Application.dataPath, newScriptPath); var chosenTextAsset = AssetDatabase.LoadAssetAtPath(relativePath); - + if (chosenTextAsset == null) { Debug.LogWarning($"Selected script couldn't be loaded ({relativePath})"); return; } - + Undo.RegisterCompleteObjectUndo(command.context, "Changing component script"); - + var so = new SerializedObject(monoBehaviour); var scriptProperty = so.FindProperty("m_Script"); so.Update(); diff --git a/Editor/NEG.Utils.Editor.asmdef b/Editor/NEG.Utils.Editor.asmdef index 60746f0..b11b4e4 100644 --- a/Editor/NEG.Utils.Editor.asmdef +++ b/Editor/NEG.Utils.Editor.asmdef @@ -1,18 +1,18 @@ { - "name": "NEG.Utils.Editor", - "rootNamespace": "", - "references": [ - "GUID:3c4294719a93e3c4e831a9ff0c261e8a" - ], - "includePlatforms": [ - "Editor" - ], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false + "name": "NEG.Utils.Editor", + "rootNamespace": "", + "references": [ + "GUID:3c4294719a93e3c4e831a9ff0c261e8a" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false } \ No newline at end of file diff --git a/Editor/ReadOnlyAttribute.cs b/Editor/ReadOnlyAttribute.cs index 956c85b..4ce718d 100644 --- a/Editor/ReadOnlyAttribute.cs +++ b/Editor/ReadOnlyAttribute.cs @@ -3,10 +3,12 @@ using UnityEngine; namespace NegUtils.Editor { - public class ReadOnlyAttribute : PropertyAttribute { } - + public class ReadOnlyAttribute : PropertyAttribute + { + } + [CustomPropertyDrawer(typeof(ReadOnlyAttribute))] - public class ReadOnlyPropertyDrawer : PropertyDrawer + public class ReadOnlyPropertyDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { @@ -15,9 +17,7 @@ namespace NegUtils.Editor GUI.enabled = true; } - public override float GetPropertyHeight(SerializedProperty property, GUIContent label) - { - return EditorGUI.GetPropertyHeight(property, label, true); - } + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) => + EditorGUI.GetPropertyHeight(property, label, true); } } \ No newline at end of file diff --git a/Editor/RequireInterfaceDrawer.cs b/Editor/RequireInterfaceDrawer.cs index 5535ce5..e54c75c 100644 --- a/Editor/RequireInterfaceDrawer.cs +++ b/Editor/RequireInterfaceDrawer.cs @@ -1,5 +1,6 @@ -using UnityEngine; using UnityEditor; +using UnityEngine; + /// /// Drawer for the RequireInterface attribute. /// @@ -10,7 +11,7 @@ namespace NEG.Utils public class RequireInterfaceDrawer : PropertyDrawer { /// - /// Overrides GUI drawing for the attribute. + /// Overrides GUI drawing for the attribute. /// /// Position. /// Property. @@ -21,11 +22,12 @@ namespace NEG.Utils if (property.propertyType == SerializedPropertyType.ObjectReference) { // Get attribute parameters. - var requiredAttribute = this.attribute as RequireInterfaceAttribute; + var requiredAttribute = attribute as RequireInterfaceAttribute; // Begin drawing property field. EditorGUI.BeginProperty(position, label, property); // Draw property field. - property.objectReferenceValue = EditorGUI.ObjectField(position, label, property.objectReferenceValue, requiredAttribute.requiredType, true); + property.objectReferenceValue = EditorGUI.ObjectField(position, label, property.objectReferenceValue, + requiredAttribute.requiredType, true); // Finish drawing property field. EditorGUI.EndProperty(); } diff --git a/Editor/ScreenshotMaker.cs b/Editor/ScreenshotMaker.cs index 7304f1c..d133c52 100644 --- a/Editor/ScreenshotMaker.cs +++ b/Editor/ScreenshotMaker.cs @@ -1,5 +1,4 @@ -using System.IO; -using UnityEditor; +using UnityEditor; using UnityEngine; namespace NEG.Editor @@ -14,8 +13,6 @@ namespace NEG.Editor return; ScreenCapture.CaptureScreenshot(path); - } - } } \ No newline at end of file diff --git a/Editor/SerializationExtentions.cs b/Editor/SerializationExtentions.cs index 2e37ad4..c4ff416 100644 --- a/Editor/SerializationExtentions.cs +++ b/Editor/SerializationExtentions.cs @@ -1,20 +1,15 @@ -using System; using UnityEditor; namespace NEG.Utils.Serialization { public static class SerializationExtentions { - public static SerializedProperty FindAutoProperty(this SerializedObject @this, string name) - { - return @this.FindProperty(GetBackingFieldName(name)); - } + public static SerializedProperty FindAutoProperty(this SerializedObject @this, string name) => + @this.FindProperty(GetBackingFieldName(name)); + + public static SerializedProperty FindAutoPropertyRelative(this SerializedProperty @this, string name) => + @this.FindPropertyRelative(GetBackingFieldName(name)); - public static SerializedProperty FindAutoPropertyRelative(this SerializedProperty @this, string name) - { - return @this.FindPropertyRelative(GetBackingFieldName(name)); - } - public static string GetBackingFieldName(string name) { #if NET_STANDARD || NET_STANDARD_2_1 @@ -29,4 +24,4 @@ namespace NEG.Utils.Serialization #endif } } -} +} \ No newline at end of file diff --git a/Editor/ToolsWindowBase.cs b/Editor/ToolsWindowBase.cs index 6248f15..78be03b 100644 --- a/Editor/ToolsWindowBase.cs +++ b/Editor/ToolsWindowBase.cs @@ -1,5 +1,4 @@ -using System; -using System.IO; +using System.IO; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; @@ -11,12 +10,33 @@ namespace NegUtils.Editor public class ToolsWindowBase : EditorWindow { private const int UnitySceneExtensionLength = 6; - + static ToolsWindowBase() { EditorApplication.playModeStateChanged += OnPlayModeStateChanged; } + protected virtual void OnGUI() + { + if (GUILayout.Button("Select Scene")) + ShowScenesList(GUILayoutUtility.GetLastRect()); + + bool startFromSceneIndex0 = EditorPrefs.GetBool("StartFromSceneIndex0"); + bool newVal = GUILayout.Toggle(startFromSceneIndex0, "Start from scene with index 0 on start"); + if (newVal != startFromSceneIndex0) EditorPrefs.SetBool("StartFromSceneIndex0", newVal); + + if (!startFromSceneIndex0) + return; + + bool goToCurrentScene = EditorPrefs.GetBool("GoToCurrentSceneAfterPlay"); + newVal = GUILayout.Toggle(goToCurrentScene, "Go to current scene after play"); + if (newVal != goToCurrentScene) EditorPrefs.SetBool("GoToCurrentSceneAfterPlay", newVal); + + bool goToFirstScene = EditorPrefs.GetBool("GoToFirstSceneAfterPlay"); + newVal = GUILayout.Toggle(goToFirstScene, "Go to scene with index 1 after play"); + if (newVal != goToFirstScene) EditorPrefs.SetBool("GoToFirstSceneAfterPlay", newVal); + } + [MenuItem("Tools/Show Tools Window")] private static void ShowWindow() { @@ -24,44 +44,14 @@ namespace NegUtils.Editor window.Show(); } - protected virtual void OnGUI() - { - if (GUILayout.Button("Select Scene")) - ShowScenesList(GUILayoutUtility.GetLastRect()); - - bool startFromSceneIndex0 = EditorPrefs.GetBool("StartFromSceneIndex0"); - bool newVal = GUILayout.Toggle(startFromSceneIndex0, "Start from scene with index 0 on start"); - if (newVal != startFromSceneIndex0) - { - EditorPrefs.SetBool("StartFromSceneIndex0", newVal); - } - - if (!startFromSceneIndex0) - return; - - bool goToCurrentScene = EditorPrefs.GetBool("GoToCurrentSceneAfterPlay"); - newVal = GUILayout.Toggle(goToCurrentScene, "Go to current scene after play"); - if (newVal != goToCurrentScene) - { - EditorPrefs.SetBool("GoToCurrentSceneAfterPlay", newVal); - } - - bool goToFirstScene = EditorPrefs.GetBool("GoToFirstSceneAfterPlay"); - newVal = GUILayout.Toggle(goToFirstScene, "Go to scene with index 1 after play"); - if (newVal != goToFirstScene) - { - EditorPrefs.SetBool("GoToFirstSceneAfterPlay", newVal); - } - } - private static void ShowScenesList(Rect position) { var menu = new GenericMenu(); - + string path = Application.dataPath + "/Scenes/Production"; - + AddFiles(path, path, menu); - + menu.DropDown(position); } @@ -71,21 +61,22 @@ namespace NegUtils.Editor for (int i = 0; i < fileInfo.Length; i++) { string s = fileInfo[i]; - menu.AddItem(new GUIContent(s.Remove(0, basePath.Length + 1).Remove(s.Length - basePath.Length - UnitySceneExtensionLength - 1 ,UnitySceneExtensionLength).Replace('\\', '/')), false, () => { - LoadScene(s); - }); - - if(i == fileInfo.Length) continue; + menu.AddItem( + new GUIContent(s.Remove(0, basePath.Length + 1) + .Remove(s.Length - basePath.Length - UnitySceneExtensionLength - 1, UnitySceneExtensionLength) + .Replace('\\', '/')), false, () => + { + LoadScene(s); + }); + + if (i == fileInfo.Length) continue; menu.AddSeparator(""); } string[] dirInfo = Directory.GetDirectories(path); - foreach (string dir in dirInfo) - { - AddFiles(dir, basePath, menu); - } + foreach (string dir in dirInfo) AddFiles(dir, basePath, menu); } - + private static void LoadScene(string path) { EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo(); @@ -94,11 +85,11 @@ namespace NegUtils.Editor private static void OnPlayModeStateChanged(PlayModeStateChange state) { - switch(state) + switch (state) { case PlayModeStateChange.ExitingEditMode: { - if(!EditorPrefs.GetBool("StartFromSceneIndex0")) + if (!EditorPrefs.GetBool("StartFromSceneIndex0")) return; EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo(); EditorPrefs.SetString("LastOpenedScenePath", EditorSceneManager.GetSceneManagerSetup()[0].path); @@ -107,7 +98,7 @@ namespace NegUtils.Editor break; case PlayModeStateChange.EnteredPlayMode: { - if(!EditorPrefs.GetBool("StartFromSceneIndex0")) + if (!EditorPrefs.GetBool("StartFromSceneIndex0")) return; if (EditorPrefs.GetBool("GoToCurrentSceneAfterPlay")) @@ -119,13 +110,12 @@ namespace NegUtils.Editor break; case PlayModeStateChange.EnteredEditMode: { - if(!EditorPrefs.GetBool("StartFromSceneIndex0")) + if (!EditorPrefs.GetBool("StartFromSceneIndex0")) return; EditorSceneManager.OpenScene(EditorPrefs.GetString("LastOpenedScenePath")); } break; } - } } } \ No newline at end of file diff --git a/Editor/TsvImporter.cs b/Editor/TsvImporter.cs index 77299f5..b580d43 100644 --- a/Editor/TsvImporter.cs +++ b/Editor/TsvImporter.cs @@ -1,9 +1,7 @@ using System.IO; -using UnityEditor; using UnityEditor.AssetImporters; -using UnityEditor.Experimental.AssetImporters; using UnityEngine; - + [ScriptedImporter(1, "tsv")] public class TsvImporter : ScriptedImporter { @@ -13,4 +11,4 @@ public class TsvImporter : ScriptedImporter ctx.AddObjectToAsset(Path.GetFileNameWithoutExtension(ctx.assetPath), textAsset); ctx.SetMainObject(textAsset); } -} +} \ No newline at end of file diff --git a/KeyBasedFactory.cs b/KeyBasedFactory.cs index c4d4d5f..8ff9c46 100644 --- a/KeyBasedFactory.cs +++ b/KeyBasedFactory.cs @@ -7,8 +7,7 @@ namespace NEG.Utils { public class KeyBasedFactory { - [PublicAPI] - protected Dictionary data; + [PublicAPI] protected Dictionary data; public KeyBasedFactory() { @@ -18,10 +17,10 @@ namespace NEG.Utils public void FireRegistration() { ScanAssembly(typeof(T2).Assembly); - - if(typeof(T2).Assembly.GetType().Assembly == typeof(T2).Assembly) + + if (typeof(T2).Assembly.GetType().Assembly == typeof(T2).Assembly) return; - + ScanAssembly(typeof(T2).Assembly.GetType().Assembly); } @@ -32,12 +31,8 @@ namespace NEG.Utils var methodFields = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < methodFields.Length; i++) - { if (Attribute.GetCustomAttribute(methodFields[i], typeof(FactoryRegistration)) != null) - { methodFields[i].Invoke(null, Array.Empty()); - } - } } } @@ -49,6 +44,5 @@ namespace NEG.Utils [AttributeUsage(AttributeTargets.Method)] public class FactoryRegistration : Attribute { - public FactoryRegistration() { } } } \ No newline at end of file diff --git a/NEG.Utils.asmdef b/NEG.Utils.asmdef index 1f68761..b750357 100644 --- a/NEG.Utils.asmdef +++ b/NEG.Utils.asmdef @@ -1,16 +1,16 @@ { - "name": "NEG.Utils", - "rootNamespace": "", - "references": [ - "GUID:6055be8ebefd69e48b49212b09b47b2f" - ], - "includePlatforms": [], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false + "name": "NEG.Utils", + "rootNamespace": "", + "references": [ + "GUID:6055be8ebefd69e48b49212b09b47b2f" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false } \ No newline at end of file diff --git a/NEG/UI/IControllable.cs b/NEG/UI/IControllable.cs index b821427..9b1a04e 100644 --- a/NEG/UI/IControllable.cs +++ b/NEG/UI/IControllable.cs @@ -4,15 +4,15 @@ namespace NegUtils.NEG.UI { public interface IControllable { + event Action OnOpened; + event Action OnClosed; + event Action OnBackUsed; + + public void TryUseBack(ref BackUsed backUsed); + public class BackUsed { public bool Used { get; set; } } - - event Action OnOpened; - event Action OnClosed; - event Action OnBackUsed; - - public void TryUseBack(ref BackUsed backUsed); } } \ No newline at end of file diff --git a/NEG/UI/NEG.UI.asmdef b/NEG/UI/NEG.UI.asmdef index 62f697c..0ee754c 100644 --- a/NEG/UI/NEG.UI.asmdef +++ b/NEG/UI/NEG.UI.asmdef @@ -1,14 +1,16 @@ { - "name": "NEG.UI", - "rootNamespace": "", - "references": ["GUID:3c4294719a93e3c4e831a9ff0c261e8a"], - "includePlatforms": [], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false + "name": "NEG.UI", + "rootNamespace": "", + "references": [ + "GUID:3c4294719a93e3c4e831a9ff0c261e8a" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false } \ No newline at end of file diff --git a/NEG/UI/Popup/DefaultPopupData.cs b/NEG/UI/Popup/DefaultPopupData.cs index bcbbefb..85fbaad 100644 --- a/NEG/UI/Popup/DefaultPopupData.cs +++ b/NEG/UI/Popup/DefaultPopupData.cs @@ -5,13 +5,14 @@ namespace NEG.UI.Popup { public class DefaultPopupData : PopupData { - private readonly IDefaultPopup defaultPopup; - - private readonly string title; private readonly string content; + private readonly IDefaultPopup defaultPopup; private readonly List<(string, Action)> options; - public DefaultPopupData(IDefaultPopup popup, string title, string content, List<(string, Action)> options) : base(popup) + private readonly string title; + + public DefaultPopupData(IDefaultPopup popup, string title, string content, List<(string, Action)> options) : + base(popup) { defaultPopup = popup; this.title = title; diff --git a/NEG/UI/Popup/IDefaultPopup.cs b/NEG/UI/Popup/IDefaultPopup.cs index 6a9216d..e15b333 100644 --- a/NEG/UI/Popup/IDefaultPopup.cs +++ b/NEG/UI/Popup/IDefaultPopup.cs @@ -6,11 +6,14 @@ namespace NEG.UI.Popup public interface IDefaultPopup : IPopup { /// - /// Sets content based on provided data. + /// Sets content based on provided data. /// /// popup title /// popup content - /// list of tuples (name, action on click), to set buttons. Do not pass here popup closing logic, implementing class should do it + /// + /// list of tuples (name, action on click), to set buttons. Do not pass here popup closing logic, + /// implementing class should do it + /// public void SetContent(string title, string content, List<(string name, Action action)> options); } } \ No newline at end of file diff --git a/NEG/UI/Popup/IPopup.cs b/NEG/UI/Popup/IPopup.cs index e3468c7..217f4ed 100644 --- a/NEG/UI/Popup/IPopup.cs +++ b/NEG/UI/Popup/IPopup.cs @@ -7,18 +7,18 @@ namespace NEG.UI.Popup public interface IPopup { /// - /// Event to fire when popup is closed + /// Event to fire when popup is closed /// event Action OnPopupClosed; /// - /// Show popup + /// Show popup /// /// data assigned to popup, used to give info that popup is closed public void Show(PopupData data); /// - /// Close popup or mark as closed if not visible + /// Close popup or mark as closed if not visible /// /// if true hide visually, without firing callbacks to properly close void Close(bool silent = false); diff --git a/NEG/UI/Popup/PopupData.cs b/NEG/UI/Popup/PopupData.cs index 9aa2462..0352b7e 100644 --- a/NEG/UI/Popup/PopupData.cs +++ b/NEG/UI/Popup/PopupData.cs @@ -6,8 +6,25 @@ namespace NEG.UI.Popup [PublicAPI] public class PopupData { + private readonly IPopup popup; + /// - /// Event that is fired on closing popup. + /// PopupData constructor. + /// + /// attached to this data, can be used by different data instances + public PopupData(IPopup popup) + { + this.popup = popup; + IsValid = true; + } + + /// + /// Is this data is still valid. If set to false, popup will not show. + /// + public bool IsValid { get; protected set; } + + /// + /// Event that is fired on closing popup. /// public event Action PopupClosedEvent { @@ -16,34 +33,17 @@ namespace NEG.UI.Popup } /// - /// Is this data is still valid. If set to false, popup will not show. - /// - public bool IsValid { get; protected set; } - - private readonly IPopup popup; - - /// - /// PopupData constructor. - /// - /// attached to this data, can be used by different data instances - public PopupData(IPopup popup) - { - this.popup = popup; - IsValid = true; - } - - /// - /// Show popup and pass needed data. + /// Show popup and pass needed data. /// public virtual void Show() => popup.Show(this); - + /// - /// Hide popup. Close visuals without firing events; + /// Hide popup. Close visuals without firing events; /// public virtual void Hide() => popup.Close(true); /// - /// Invalidate popup, will automatically skip this popup + /// Invalidate popup, will automatically skip this popup /// public virtual void Invalidate() { diff --git a/NEG/UI/PriorityQueue.cs b/NEG/UI/PriorityQueue.cs index 74e3e1b..591e85f 100644 --- a/NEG/UI/PriorityQueue.cs +++ b/NEG/UI/PriorityQueue.cs @@ -489,7 +489,7 @@ namespace System.Collections.Generic { int i = 0; (TElement, TPriority)[] nodes = _nodes; - foreach ((var element, var priority) in items) + foreach (var (element, priority) in items) { if (nodes.Length == i) { @@ -509,7 +509,7 @@ namespace System.Collections.Generic } else { - foreach ((var element, var priority) in items) Enqueue(element, priority); + foreach (var (element, priority) in items) Enqueue(element, priority); } } diff --git a/NEG/UI/UiManager.cs b/NEG/UI/UiManager.cs index f55b0da..1a4783b 100644 --- a/NEG/UI/UiManager.cs +++ b/NEG/UI/UiManager.cs @@ -2,7 +2,6 @@ using JetBrains.Annotations; using NEG.UI.Area; using NEG.UI.Popup; using NEG.UI.Window; -using NEG.Utils; using NegUtils.NEG.UI; using System; using System.Collections.Generic; @@ -14,42 +13,17 @@ namespace NEG.UI [PublicAPI] public abstract class UiManager : IDisposable { - public static UiManager Instance { get; protected set; } - - /// - /// Current area shown on screen. - /// - public IArea CurrentArea - { - get => currentArea; - set - { - currentArea?.Close(); - - currentArea = value; - - currentArea?.Open(); - } - } - - /// - /// Current window that is considered main (focused, lastly opened). Can be null. - /// - public IWindow CurrentMainWindow => mainWindows.LastOrDefault(); - - public PopupData CurrentPopup => currentShownPopup.data; - private IArea currentArea; - private (PopupData data, int priority) currentShownPopup; protected IDefaultPopup currentDefaultPopup; - - private PriorityQueue popupsToShow = new(); + private (PopupData data, int priority) currentShownPopup; //TODO: localize private string localizedYes = "Yes", localizedNo = "No", localizedOk = "Ok"; private List mainWindows; + private PriorityQueue popupsToShow = new(); + protected UiManager(IArea startArea) { if (Instance != null) @@ -64,8 +38,36 @@ namespace NEG.UI mainWindows = new List(); } + public static UiManager Instance { get; protected set; } + /// - /// Show popup if there is non other currently shown. Otherwise add current popup to ordered queue and show it later. It will be closed after pressing ok button. + /// Current area shown on screen. + /// + public IArea CurrentArea + { + get => currentArea; + set + { + currentArea?.Close(); + + currentArea = value; + + currentArea?.Open(); + } + } + + /// + /// Current window that is considered main (focused, lastly opened). Can be null. + /// + public IWindow CurrentMainWindow => mainWindows.LastOrDefault(); + + public PopupData CurrentPopup => currentShownPopup.data; + + public virtual void Dispose() => Instance = null; + + /// + /// Show popup if there is non other currently shown. Otherwise add current popup to ordered queue and show it later. + /// It will be closed after pressing ok button. /// /// popup title /// popup content @@ -74,16 +76,18 @@ namespace NEG.UI /// priority of popup (lower number -> show first) /// force show current popup only if currently shown has lower priority /// data for created popup, can be used to invalidate popup (will not show) - public PopupData ShowOkPopup(string title, string content, string okText = null, Action okPressed = null, int priority = 0, bool forceShow = false) + public PopupData ShowOkPopup(string title, string content, string okText = null, Action okPressed = null, + int priority = 0, bool forceShow = false) { var data = new DefaultPopupData(currentDefaultPopup, title, content, - new List<(string, Action)>() { (okText ?? localizedOk, okPressed) }); + new List<(string, Action)> { (okText ?? localizedOk, okPressed) }); ShowPopup(data, priority, forceShow); return data; } - + /// - /// Show popup if there is non other currently shown. Otherwise add current popup to ordered queue and show it later. It will be closed after pressing yes or no button. + /// Show popup if there is non other currently shown. Otherwise add current popup to ordered queue and show it later. + /// It will be closed after pressing yes or no button. /// /// popup title /// popup content @@ -94,16 +98,21 @@ namespace NEG.UI /// priority of popup (lower number -> show first) /// force show current popup only if currently shown has lower priority /// data for created popup, can be used to invalidate popup (will not show) - public PopupData ShowYesNoPopup(string title, string content, string yesText = null, string noText = null, Action yesPressed = null, Action noPressed = null, int priority = 0, bool forceShow = false) + public PopupData ShowYesNoPopup(string title, string content, string yesText = null, string noText = null, + Action yesPressed = null, Action noPressed = null, int priority = 0, bool forceShow = false) { var data = new DefaultPopupData(currentDefaultPopup, title, content, - new List<(string, Action)>() { (yesText ?? localizedYes, yesPressed), (noText ?? localizedNo, noPressed) }); + new List<(string, Action)> + { + (yesText ?? localizedYes, yesPressed), (noText ?? localizedNo, noPressed) + }); ShowPopup(data, priority, forceShow); return data; } - + /// - /// Show popup if there is non other currently shown. Otherwise add current popup to ordered queue and show it later. It will be closed after pressing any button. + /// Show popup if there is non other currently shown. Otherwise add current popup to ordered queue and show it later. + /// It will be closed after pressing any button. /// /// popup title /// popup content @@ -111,15 +120,16 @@ namespace NEG.UI /// priority of popup (lower number -> show first) /// force show current popup only if currently shown has lower priority /// data for created popup, can be used to invalidate popup (will not show) - public PopupData ShowPopup(string title, string content, List<(string, Action)> actions, int priority = 0, bool forceShow = false) + public PopupData ShowPopup(string title, string content, List<(string, Action)> actions, int priority = 0, + bool forceShow = false) { var data = new DefaultPopupData(currentDefaultPopup, title, content, actions); ShowPopup(data, priority, forceShow); return data; } - + /// - /// Show popup if there is non other currently shown. Otherwise add current popup to ordered queue and show it later. + /// Show popup if there is non other currently shown. Otherwise add current popup to ordered queue and show it later. /// /// popup data object /// priority of popup (lower number -> show first) @@ -135,22 +145,20 @@ namespace NEG.UI IControllable.BackUsed backUsed = new(); CurrentMainWindow?.TryUseBack(ref backUsed); - if(backUsed.Used) + if (backUsed.Used) return; CurrentArea.TryUseBack(ref backUsed); } - + public void RefreshPopups() { - if(currentShownPopup.data is { IsValid: true }) + if (currentShownPopup.data is { IsValid: true }) return; UpdatePopupsState(false); } - public virtual void Dispose() => Instance = null; - - public void SetMainWindow(IWindow window) => mainWindows.Add(window); + public void SetMainWindow(IWindow window) => mainWindows.Add(window); public void MainWindowClosed(IWindow window) => mainWindows.Remove(window); @@ -160,10 +168,8 @@ namespace NEG.UI protected void PopupClosed(PopupData data) { if (currentShownPopup.data != data) - { //Debug.LogError("Popup was not shown"); return; - } UpdatePopupsState(false); } @@ -174,9 +180,9 @@ namespace NEG.UI { if (forceShow) { - if(currentShownPopup.data != null && currentShownPopup.priority >= priority) + if (currentShownPopup.data != null && currentShownPopup.priority >= priority) return; - + popupsToShow.Enqueue(currentShownPopup.data, currentShownPopup.priority); ShowPopup(data, priority); return; @@ -184,17 +190,17 @@ namespace NEG.UI while (popupsToShow.TryDequeue(out var d, out int p)) { - if(d == null) + if (d == null) continue; - if(!d.IsValid) + if (!d.IsValid) continue; - if(d == currentShownPopup.data) + if (d == currentShownPopup.data) continue; ShowPopup(d, p); return; } - if (currentShownPopup.data == null) + if (currentShownPopup.data == null) return; currentShownPopup.data.PopupClosedEvent -= PopupClosed; currentShownPopup.data.Hide(); @@ -208,11 +214,10 @@ namespace NEG.UI currentShownPopup.data.PopupClosedEvent -= PopupClosed; currentShownPopup.data.Hide(); } + currentShownPopup = (data, priority); data.Show(); data.PopupClosedEvent += PopupClosed; } } -} - - +} \ No newline at end of file diff --git a/NEG/UI/UnityUi/Area/AutoOpenWindowWhenNoOther.cs b/NEG/UI/UnityUi/Area/AutoOpenWindowWhenNoOther.cs index c9ba380..92ddc7e 100644 --- a/NEG/UI/UnityUi/Area/AutoOpenWindowWhenNoOther.cs +++ b/NEG/UI/UnityUi/Area/AutoOpenWindowWhenNoOther.cs @@ -10,7 +10,7 @@ namespace NEG.UI.Area private void Start() { - if(UiManager.Instance.CurrentMainWindow == null) + if (UiManager.Instance.CurrentMainWindow == null) window.Open(); } } diff --git a/NEG/UI/UnityUi/Area/AutoWindowOpen.cs b/NEG/UI/UnityUi/Area/AutoWindowOpen.cs index 48e1f64..aa14eb0 100644 --- a/NEG/UI/UnityUi/Area/AutoWindowOpen.cs +++ b/NEG/UI/UnityUi/Area/AutoWindowOpen.cs @@ -1,16 +1,14 @@ using NEG.UI.UnityUi.Window; using NEG.UI.Window; -using System; -using KBCore.Refs; using UnityEngine; namespace NEG.UI.Area { - [Tooltip(tooltip: "Automatically open attached window on start")] + [Tooltip("Automatically open attached window on start")] public class AutoWindowOpen : MonoBehaviour { [SerializeField] private MonoWindow window; - + private void Start() => window.Open(); } } \ No newline at end of file diff --git a/NEG/UI/UnityUi/Area/CloseMainWindowOnBack.cs b/NEG/UI/UnityUi/Area/CloseMainWindowOnBack.cs index b7211c5..84f03a8 100644 --- a/NEG/UI/UnityUi/Area/CloseMainWindowOnBack.cs +++ b/NEG/UI/UnityUi/Area/CloseMainWindowOnBack.cs @@ -1,9 +1,6 @@ -using KBCore.Refs; -using NEG.UI.UnityUi; +using NEG.UI.UnityUi; using NEG.UI.Window; using NegUtils.NEG.UI; -using System; -using UnityEngine; namespace NEG.UI.Area { diff --git a/NEG/UI/UnityUi/Area/MonoArea.cs b/NEG/UI/UnityUi/Area/MonoArea.cs index 535489a..f9e09da 100644 --- a/NEG/UI/UnityUi/Area/MonoArea.cs +++ b/NEG/UI/UnityUi/Area/MonoArea.cs @@ -1,40 +1,19 @@ -using System.Collections.Generic; -using UnityEngine; -using NEG.UI.Popup; -using NEG.UI.UnityUi.Window; -using NEG.UI.UnityUi.WindowSlot; +using NEG.UI.UnityUi.WindowSlot; using NEG.UI.Window; using NEG.UI.WindowSlot; using NegUtils.NEG.UI; using System; +using System.Collections.Generic; +using UnityEngine; namespace NEG.UI.Area { public class MonoArea : MonoBehaviour, IArea { - public event Action OnOpened; - public event Action OnClosed; - public event Action OnBackUsed; - - public IEnumerable AvailableSlots => windowSlots; - public IWindowSlot DefaultWindowSlot => windowSlots[0]; - [SerializeField] private bool setAsDefaultArea; [SerializeField] private List windowSlots; - - public void Open() - { - gameObject.SetActive(true); - OnOpened?.Invoke(null); - } - - public void Close(){ - gameObject.SetActive(false); - OnClosed?.Invoke(); - } - - public void OpenWindow(IWindow window, object data = null) => DefaultWindowSlot.AttachWindow(window, data); + public IWindowSlot DefaultWindowSlot => windowSlots[0]; protected virtual void Awake() { @@ -44,7 +23,7 @@ namespace NEG.UI.Area private void Start() { - if(!setAsDefaultArea) + if (!setAsDefaultArea) Close(); } @@ -54,6 +33,26 @@ namespace NEG.UI.Area UiManager.Instance.CurrentArea = null; } + public event Action OnOpened; + public event Action OnClosed; + public event Action OnBackUsed; + + public IEnumerable AvailableSlots => windowSlots; + + public void Open() + { + gameObject.SetActive(true); + OnOpened?.Invoke(null); + } + + public void Close() + { + gameObject.SetActive(false); + OnClosed?.Invoke(); + } + + public void OpenWindow(IWindow window, object data = null) => DefaultWindowSlot.AttachWindow(window, data); + public void TryUseBack(ref IControllable.BackUsed backUsed) => OnBackUsed?.Invoke(backUsed); } } \ No newline at end of file diff --git a/NEG/UI/UnityUi/Buttons/BaseButton.cs b/NEG/UI/UnityUi/Buttons/BaseButton.cs index 939bdbf..4253e94 100644 --- a/NEG/UI/UnityUi/Buttons/BaseButton.cs +++ b/NEG/UI/UnityUi/Buttons/BaseButton.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.EventSystems; -using UnityEngine.Serialization; using UnityEngine.UI; namespace NEG.UI.UnityUi.Buttons @@ -16,65 +15,23 @@ namespace NEG.UI.UnityUi.Buttons public class BaseButton : MonoBehaviour, ISelectHandler, IDeselectHandler, IPointerEnterHandler, IPointerExitHandler { public delegate void SelectionHandler(bool isSilent); - /// - /// is silent - /// - public event SelectionHandler OnSelected; - public event SelectionHandler OnDeselected; - public event Action OnButtonPressed; + + [SerializeField] [Self(Flag.Optional)] private Button button; + + [SerializeField] [Child(Flag.Optional)] + private TMP_Text text; + + [SerializeField] [Child(Flag.Optional)] + private Image icon; + + [SerializeField] private ButtonSettings groupButtonSettings; + + private readonly Dictionary behaviours = new(); public bool Interactable { get => button.interactable; set => button.interactable = value; } public TMP_Text Text => text; - [SerializeField, Self(Flag.Optional)] private Button button; - [SerializeField, Child(Flag.Optional)] private TMP_Text text; - [SerializeField, Child(Flag.Optional)] private Image icon; - - [SerializeField] private ButtonSettings groupButtonSettings; - - private readonly Dictionary behaviours = new Dictionary(); - - public virtual void OnSelect(BaseEventData eventData) => OnSelected?.Invoke(eventData is SilentEventData); - - public void OnDeselect(BaseEventData eventData) => OnDeselected?.Invoke(eventData is SilentEventData); - - public void OnPointerEnter(PointerEventData eventData) => EventSystem.current.SetSelectedGameObject(gameObject); - - public void OnPointerExit(PointerEventData eventData) - { - if(EventSystem.current.currentSelectedGameObject == gameObject) - EventSystem.current.SetSelectedGameObject(null); - } - - public void SetText(string txt) - { - if(text == null) - return; - text.text = txt; - } - - public void AddOrOverrideSetting(SettingData data) - { - if (behaviours.TryGetValue(data.Key, out var setting)) - { - setting.ChangeData(data); - return; - } - behaviours.Add(data.Key, MonoUiManager.Instance.BehavioursFactory.CreateInstance(data.Key, this, data)); - } - - public void RemoveSetting(string key) - { - if (!behaviours.TryGetValue(key, out var setting)) - { - Debug.LogError($"Behaviour with key {key} was not found"); - return; - } - setting.Dispose(); - behaviours.Remove(key); - } - protected virtual void Awake() { button.onClick.AddListener(OnClicked); @@ -88,10 +45,60 @@ namespace NEG.UI.UnityUi.Buttons private void OnValidate() => this.ValidateRefs(); + public void OnDeselect(BaseEventData eventData) => OnDeselected?.Invoke(eventData is SilentEventData); + + public void OnPointerEnter(PointerEventData eventData) => EventSystem.current.SetSelectedGameObject(gameObject); + + public void OnPointerExit(PointerEventData eventData) + { + if (EventSystem.current.currentSelectedGameObject == gameObject) + EventSystem.current.SetSelectedGameObject(null); + } + + public virtual void OnSelect(BaseEventData eventData) => OnSelected?.Invoke(eventData is SilentEventData); + + /// + /// is silent + /// + public event SelectionHandler OnSelected; + + public event SelectionHandler OnDeselected; + public event Action OnButtonPressed; + + public void SetText(string txt) + { + if (text == null) + return; + text.text = txt; + } + + public void AddOrOverrideSetting(SettingData data) + { + if (behaviours.TryGetValue(data.Key, out var setting)) + { + setting.ChangeData(data); + return; + } + + behaviours.Add(data.Key, MonoUiManager.Instance.BehavioursFactory.CreateInstance(data.Key, this, data)); + } + + public void RemoveSetting(string key) + { + if (!behaviours.TryGetValue(key, out var setting)) + { + Debug.LogError($"Behaviour with key {key} was not found"); + return; + } + + setting.Dispose(); + behaviours.Remove(key); + } + protected virtual void OnClicked() { OnDeselect(null); OnButtonPressed?.Invoke(); } } -} +} \ No newline at end of file diff --git a/NEG/UI/UnityUi/Buttons/ButtonReaction.cs b/NEG/UI/UnityUi/Buttons/ButtonReaction.cs index c2c2590..0cd17af 100644 --- a/NEG/UI/UnityUi/Buttons/ButtonReaction.cs +++ b/NEG/UI/UnityUi/Buttons/ButtonReaction.cs @@ -1,5 +1,4 @@ -using System; -using KBCore.Refs; +using KBCore.Refs; using UnityEngine; namespace NEG.UI.UnityUi.Buttons @@ -7,8 +6,8 @@ namespace NEG.UI.UnityUi.Buttons [RequireComponent(typeof(BaseButton))] public abstract class ButtonReaction : MonoBehaviour { - [SerializeField, Self(Flag.Optional)] protected BaseButton button; - + [SerializeField] [Self(Flag.Optional)] protected BaseButton button; + protected virtual void Awake() => button.OnButtonPressed += OnClicked; protected virtual void OnDestroy() => button.OnButtonPressed -= OnClicked; diff --git a/NEG/UI/UnityUi/Buttons/ChangeSceneButton.cs b/NEG/UI/UnityUi/Buttons/ChangeSceneButton.cs index b6cc168..7518523 100644 --- a/NEG/UI/UnityUi/Buttons/ChangeSceneButton.cs +++ b/NEG/UI/UnityUi/Buttons/ChangeSceneButton.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections; -using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; @@ -9,8 +6,8 @@ namespace NEG.UI.UnityUi.Buttons [RequireComponent(typeof(BaseButton))] public class ChangeSceneButton : ButtonReaction { - [Header("Leave empty to use int value")] - [SerializeField] private string sceneName; + [Header("Leave empty to use int value")] [SerializeField] + private string sceneName; [SerializeField] private int sceneIndex; @@ -22,4 +19,4 @@ namespace NEG.UI.UnityUi.Buttons SceneManager.LoadScene(sceneName); } } -} +} \ No newline at end of file diff --git a/NEG/UI/UnityUi/Buttons/CloseAllWindows.cs b/NEG/UI/UnityUi/Buttons/CloseAllWindows.cs index 07fdc0c..071ad86 100644 --- a/NEG/UI/UnityUi/Buttons/CloseAllWindows.cs +++ b/NEG/UI/UnityUi/Buttons/CloseAllWindows.cs @@ -1,6 +1,4 @@ -using UnityEngine; - -namespace NEG.UI.UnityUi.Buttons +namespace NEG.UI.UnityUi.Buttons { public class CloseAllWindows : ButtonReaction { diff --git a/NEG/UI/UnityUi/Buttons/CloseWindow.cs b/NEG/UI/UnityUi/Buttons/CloseWindow.cs index 08d936e..2eb8407 100644 --- a/NEG/UI/UnityUi/Buttons/CloseWindow.cs +++ b/NEG/UI/UnityUi/Buttons/CloseWindow.cs @@ -1,6 +1,5 @@ using NEG.UI.UnityUi.Window; using NEG.UI.Window; -using System; using UnityEngine; namespace NEG.UI.UnityUi.Buttons @@ -10,13 +9,13 @@ namespace NEG.UI.UnityUi.Buttons { [SerializeField] private MonoWindow windowToClose; - protected override void OnClicked() => windowToClose.Close(); - private void OnValidate() { - if(windowToClose != null) + if (windowToClose != null) return; windowToClose = GetComponentInParent(); } + + protected override void OnClicked() => windowToClose.Close(); } } \ No newline at end of file diff --git a/NEG/UI/UnityUi/Buttons/CloseWindowOnImageTouch.cs b/NEG/UI/UnityUi/Buttons/CloseWindowOnImageTouch.cs index 4ea19c3..5a72213 100644 --- a/NEG/UI/UnityUi/Buttons/CloseWindowOnImageTouch.cs +++ b/NEG/UI/UnityUi/Buttons/CloseWindowOnImageTouch.cs @@ -8,7 +8,7 @@ namespace NEG.UI.UnityUi.Buttons public class CloseWindowOnImageTouch : MonoBehaviour, IPointerDownHandler { [SerializeField] private MonoWindow windowToClose; - + public void OnPointerDown(PointerEventData eventData) => windowToClose.Close(); } } \ No newline at end of file diff --git a/NEG/UI/UnityUi/Buttons/CustomNavigationButton.cs b/NEG/UI/UnityUi/Buttons/CustomNavigationButton.cs index e7e82eb..3a4c89b 100644 --- a/NEG/UI/UnityUi/Buttons/CustomNavigationButton.cs +++ b/NEG/UI/UnityUi/Buttons/CustomNavigationButton.cs @@ -11,26 +11,26 @@ namespace NEG.UI.UnityUi.Buttons [SerializeField] private OverridableNavigation downOverride; [SerializeField] private OverridableNavigation leftOverride; [SerializeField] private OverridableNavigation rightOverride; - - + + public override void OnMove(AxisEventData eventData) { switch (eventData.moveDir) { case MoveDirection.Left: - if(TryNavigate(eventData, leftOverride)) + if (TryNavigate(eventData, leftOverride)) return; break; case MoveDirection.Up: - if(TryNavigate(eventData, upOverride)) + if (TryNavigate(eventData, upOverride)) return; break; case MoveDirection.Right: - if(TryNavigate(eventData, rightOverride)) + if (TryNavigate(eventData, rightOverride)) return; break; case MoveDirection.Down: - if(TryNavigate(eventData, downOverride)) + if (TryNavigate(eventData, downOverride)) return; break; case MoveDirection.None: @@ -38,17 +38,18 @@ namespace NEG.UI.UnityUi.Buttons default: throw new ArgumentOutOfRangeException(); } + base.OnMove(eventData); } public static bool TryNavigate(BaseEventData eventData, OverridableNavigation overrideNavigation) { - if(!overrideNavigation.Override) + if (!overrideNavigation.Override) return false; - if (overrideNavigation.Selectable == null || !overrideNavigation.Selectable.IsActive()) + if (overrideNavigation.Selectable == null || !overrideNavigation.Selectable.IsActive()) return true; - + eventData.selectedObject = overrideNavigation.Selectable.gameObject; return true; } diff --git a/NEG/UI/UnityUi/Buttons/OpenAsCurrentMainChild.cs b/NEG/UI/UnityUi/Buttons/OpenAsCurrentMainChild.cs index 1d9bcf2..af5302e 100644 --- a/NEG/UI/UnityUi/Buttons/OpenAsCurrentMainChild.cs +++ b/NEG/UI/UnityUi/Buttons/OpenAsCurrentMainChild.cs @@ -1,5 +1,4 @@ -using KBCore.Refs; -using NEG.UI.UnityUi.Window; +using NEG.UI.UnityUi.Window; using NEG.UI.Window; using UnityEngine; @@ -7,8 +6,7 @@ namespace NEG.UI.UnityUi.Buttons { public class OpenAsCurrentMainChild : ButtonReaction { - [SerializeField] - private MonoWindow windowToOpen; + [SerializeField] private MonoWindow windowToOpen; protected override void OnClicked() => UiManager.Instance.CurrentMainWindow.OpenAsChild(windowToOpen); } diff --git a/NEG/UI/UnityUi/Buttons/OpenWindow.cs b/NEG/UI/UnityUi/Buttons/OpenWindow.cs index 08dd149..45b0cbf 100644 --- a/NEG/UI/UnityUi/Buttons/OpenWindow.cs +++ b/NEG/UI/UnityUi/Buttons/OpenWindow.cs @@ -1,9 +1,7 @@ using NEG.UI.UnityUi.Window; using NEG.UI.UnityUi.WindowSlot; -using System; -using UnityEngine; using NEG.UI.Window; -using NEG.UI.WindowSlot; +using UnityEngine; namespace NEG.UI.UnityUi.Buttons { @@ -11,8 +9,9 @@ namespace NEG.UI.UnityUi.Buttons public class OpenWindow : ButtonReaction { [SerializeField] private MonoWindow window; - [Header("Open on default area slot if empty")] - [SerializeField] private MonoWindowSlot slot; + + [Header("Open on default area slot if empty")] [SerializeField] + private MonoWindowSlot slot; protected override void OnClicked() => window.Open(slot); } diff --git a/NEG/UI/UnityUi/Buttons/Reaction/ButtonElementBehaviour.cs b/NEG/UI/UnityUi/Buttons/Reaction/ButtonElementBehaviour.cs index 7d2f96a..c5f4204 100644 --- a/NEG/UI/UnityUi/Buttons/Reaction/ButtonElementBehaviour.cs +++ b/NEG/UI/UnityUi/Buttons/Reaction/ButtonElementBehaviour.cs @@ -1,22 +1,21 @@ using NEG.UI.UnityUi.Buttons.Settings; using System; -using UnityEngine.EventSystems; namespace NEG.UI.UnityUi.Buttons.Reaction { public abstract class ButtonElementBehaviour : IDisposable { - protected SettingData baseData; protected readonly BaseButton button; - + protected SettingData baseData; + public ButtonElementBehaviour(BaseButton baseButton, SettingData settingData) { button = baseButton; baseData = settingData; } - public virtual void ChangeData(SettingData newData) => baseData = newData; - public abstract void Dispose(); + + public virtual void ChangeData(SettingData newData) => baseData = newData; } } \ No newline at end of file diff --git a/NEG/UI/UnityUi/Buttons/Reaction/ChangeTextColorBehaviour.cs b/NEG/UI/UnityUi/Buttons/Reaction/ChangeTextColorBehaviour.cs index f679698..228b388 100644 --- a/NEG/UI/UnityUi/Buttons/Reaction/ChangeTextColorBehaviour.cs +++ b/NEG/UI/UnityUi/Buttons/Reaction/ChangeTextColorBehaviour.cs @@ -1,14 +1,13 @@ using NEG.UI.UnityUi.Buttons.Settings; using NEG.Utils; using UnityEngine; -using UnityEngine.EventSystems; namespace NEG.UI.UnityUi.Buttons.Reaction { public class ChangeTextColorBehaviour : ButtonElementBehaviour { private ColorData data; - + public ChangeTextColorBehaviour(BaseButton baseButton, ColorData data) : base(baseButton, data) { if (baseButton.Text == null) @@ -31,13 +30,12 @@ namespace NEG.UI.UnityUi.Buttons.Reaction button.OnSelected -= OnButtonSelected; button.OnDeselected -= OnButtonDeselected; } - + [FactoryRegistration] private static void RegisterInFactory() => MonoUiManager.Instance.BehavioursFactory.Register("ChangeTextColor", typeof(ChangeTextColorBehaviour)); private void OnButtonSelected(bool _) => button.Text.color = data.SelectedColor; private void OnButtonDeselected(bool _) => button.Text.color = data.DeselectedColor; - } } \ No newline at end of file diff --git a/NEG/UI/UnityUi/Buttons/Reaction/SimpleSoundBehaviour.cs b/NEG/UI/UnityUi/Buttons/Reaction/SimpleSoundBehaviour.cs index 156b8c9..13386d7 100644 --- a/NEG/UI/UnityUi/Buttons/Reaction/SimpleSoundBehaviour.cs +++ b/NEG/UI/UnityUi/Buttons/Reaction/SimpleSoundBehaviour.cs @@ -1,7 +1,4 @@ -using NEG.UI.UnityUi.Buttons.Settings; -using NEG.Utils; -#if FMOD - +#if FMOD namespace NEG.UI.UnityUi.Buttons.Reaction { public class SimpleSoundBehaviour : ButtonElementBehaviour diff --git a/NEG/UI/UnityUi/Buttons/Settings/ButtonSettings.cs b/NEG/UI/UnityUi/Buttons/Settings/ButtonSettings.cs index 3486140..1f3545f 100644 --- a/NEG/UI/UnityUi/Buttons/Settings/ButtonSettings.cs +++ b/NEG/UI/UnityUi/Buttons/Settings/ButtonSettings.cs @@ -1,8 +1,5 @@ -using System; -using System.Collections.Generic; -using UnityEditor; +using System.Collections.Generic; using UnityEngine; -using UnityEngine.UI; namespace NEG.UI.UnityUi.Buttons.Settings { @@ -12,21 +9,15 @@ namespace NEG.UI.UnityUi.Buttons.Settings public void Apply(BaseButton button) { - foreach (var setting in settingDatas) - { - setting.Apply(button); - } + foreach (var setting in settingDatas) setting.Apply(button); } - + [ContextMenu("Refresh")] public void Refresh() { settingDatas.Clear(); var components = GetComponents(); - foreach (var data in components) - { - settingDatas.Add(data); - } + foreach (var data in components) settingDatas.Add(data); } } } \ No newline at end of file diff --git a/NEG/UI/UnityUi/Buttons/Settings/SettingData.cs b/NEG/UI/UnityUi/Buttons/Settings/SettingData.cs index f2ad4d2..83c0598 100644 --- a/NEG/UI/UnityUi/Buttons/Settings/SettingData.cs +++ b/NEG/UI/UnityUi/Buttons/Settings/SettingData.cs @@ -1,20 +1,16 @@ using KBCore.Refs; -using System; using UnityEngine; -using UnityEngine.Serialization; namespace NEG.UI.UnityUi.Buttons.Settings { public abstract class SettingData : MonoBehaviour { [field: SerializeField] public string Key { get; private set; } - [SerializeField, Self(Flag.Optional)] private BaseButton attachedButton; - - public virtual void Apply(BaseButton button) => button.AddOrOverrideSetting(this); + [SerializeField] [Self(Flag.Optional)] private BaseButton attachedButton; private void Awake() { - if(attachedButton != null) + if (attachedButton != null) Apply(attachedButton); } @@ -23,6 +19,8 @@ namespace NEG.UI.UnityUi.Buttons.Settings this.ValidateRefs(); if (attachedButton == null && TryGetComponent(out ButtonSettings settings)) settings.Refresh(); - } + } + + public virtual void Apply(BaseButton button) => button.AddOrOverrideSetting(this); } } \ No newline at end of file diff --git a/NEG/UI/UnityUi/CarouselList/CarouselList.cs b/NEG/UI/UnityUi/CarouselList/CarouselList.cs index e787ed1..d087ed9 100644 --- a/NEG/UI/UnityUi/CarouselList/CarouselList.cs +++ b/NEG/UI/UnityUi/CarouselList/CarouselList.cs @@ -5,23 +5,11 @@ using System.Collections.Generic; using TMPro; using UnityEngine; - namespace NEG.UI.UnityUi { [PublicAPI] public class CarouselList : MonoBehaviour { - public event Action OnSelectedItemChanged; - /// - /// Current option - /// - public string CurrentOption { get; private set; } - - /// - /// Current selected option id - /// - public int CurrentOptionId { get; private set; } - [SerializeField] private BaseButton nextButton; [SerializeField] private BaseButton prevButton; [SerializeField] private TMP_Text currentOptionText; @@ -29,7 +17,31 @@ namespace NEG.UI.UnityUi private List options; /// - /// Sets new options list, automatically first will be selected. + /// Current option + /// + public string CurrentOption { get; private set; } + + /// + /// Current selected option id + /// + public int CurrentOptionId { get; private set; } + + private void Awake() + { + nextButton.OnButtonPressed += SelectNextOption; + prevButton.OnButtonPressed += SelectPrevOption; + } + + private void OnDestroy() + { + nextButton.OnButtonPressed -= SelectNextOption; + prevButton.OnButtonPressed -= SelectPrevOption; + } + + public event Action OnSelectedItemChanged; + + /// + /// Sets new options list, automatically first will be selected. /// /// list of options names public void SetOptions(List options) @@ -40,9 +52,9 @@ namespace NEG.UI.UnityUi public void SelectNextOption() => ChangeOption(true); public void SelectPrevOption() => ChangeOption(false); - + /// - /// Selects option with provided id. + /// Selects option with provided id. /// /// option number public void SelectOption(int option) @@ -52,6 +64,7 @@ namespace NEG.UI.UnityUi Debug.LogError("Invalid option number"); return; } + CurrentOptionId = option; CurrentOption = options[option]; currentOptionText.text = CurrentOption; @@ -59,7 +72,7 @@ namespace NEG.UI.UnityUi } /// - /// Select option with provided value. Use with caution, better use . + /// Select option with provided value. Use with caution, better use . /// /// option value to select public void SelectOption(string option) @@ -76,22 +89,11 @@ namespace NEG.UI.UnityUi Debug.LogError($"Option {option} not found"); return; } - + SelectOption(index); } - private void Awake() - { - nextButton.OnButtonPressed += SelectNextOption; - prevButton.OnButtonPressed += SelectPrevOption; - } - - private void OnDestroy() - { - nextButton.OnButtonPressed -= SelectNextOption; - prevButton.OnButtonPressed -= SelectPrevOption; - } - - private void ChangeOption(bool next) => SelectOption((CurrentOptionId + (next ? 1 : -1) + options.Count) % options.Count); + private void ChangeOption(bool next) => + SelectOption((CurrentOptionId + (next ? 1 : -1) + options.Count) % options.Count); } } \ No newline at end of file diff --git a/NEG/UI/UnityUi/Editor/ButtonsExtensions.cs b/NEG/UI/UnityUi/Editor/ButtonsExtensions.cs index 5817242..58e5516 100644 --- a/NEG/UI/UnityUi/Editor/ButtonsExtensions.cs +++ b/NEG/UI/UnityUi/Editor/ButtonsExtensions.cs @@ -1,6 +1,4 @@ using NEG.UI.UnityUi.Buttons; -using System.Collections.Generic; -using System.IO; using UnityEditor; using UnityEngine; using UnityEngine.UI; @@ -20,7 +18,7 @@ namespace NEG.UI.UnityUi.Editor var sourceScriptAsset = MonoScript.FromMonoBehaviour(go.AddComponent()); string relativePath = AssetDatabase.GetAssetPath(sourceScriptAsset); Object.DestroyImmediate(go); - + var chosenTextAsset = AssetDatabase.LoadAssetAtPath(relativePath); if (chosenTextAsset == null) @@ -37,6 +35,5 @@ namespace NEG.UI.UnityUi.Editor scriptProperty.objectReferenceValue = chosenTextAsset; so.ApplyModifiedProperties(); } - } -} +} \ No newline at end of file diff --git a/NEG/UI/UnityUi/Editor/CustomNavigationButtonEditor.cs b/NEG/UI/UnityUi/Editor/CustomNavigationButtonEditor.cs index 2e92e00..de6ae4f 100644 --- a/NEG/UI/UnityUi/Editor/CustomNavigationButtonEditor.cs +++ b/NEG/UI/UnityUi/Editor/CustomNavigationButtonEditor.cs @@ -1,16 +1,16 @@ -using UnityEditor; +using NEG.UI.UnityUi.Buttons; +using UnityEditor; using UnityEditor.UI; -using UnityEngine.UIElements; namespace NEG.UI.UnityUi.Editor { - [CustomEditor(typeof(Buttons.CustomNavigationButton), true)] + [CustomEditor(typeof(CustomNavigationButton), true)] public class CustomNavigationButtonEditor : ButtonEditor { - private SerializedProperty upOverrideProperty; private SerializedProperty downOverrideProperty; private SerializedProperty leftOverrideProperty; private SerializedProperty rightOverrideProperty; + private SerializedProperty upOverrideProperty; protected override void OnEnable() { diff --git a/NEG/UI/UnityUi/Editor/NEG.UI.UnityUi.Editor.asmdef b/NEG/UI/UnityUi/Editor/NEG.UI.UnityUi.Editor.asmdef index f943876..00db363 100644 --- a/NEG/UI/UnityUi/Editor/NEG.UI.UnityUi.Editor.asmdef +++ b/NEG/UI/UnityUi/Editor/NEG.UI.UnityUi.Editor.asmdef @@ -1,21 +1,21 @@ { - "name": "NEG.UI.UnityUi.Editor", - "rootNamespace": "", - "references": [ - "GUID:e2aaf8effe1c9634d87b2edda6988a6a", - "GUID:5928dc8d9173fd348aa77d4593ca3fd8" - ], - "includePlatforms": [ - "Editor" - ], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": false, - "precompiledReferences": [ - "" - ], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false + "name": "NEG.UI.UnityUi.Editor", + "rootNamespace": "", + "references": [ + "GUID:e2aaf8effe1c9634d87b2edda6988a6a", + "GUID:5928dc8d9173fd348aa77d4593ca3fd8" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [ + "" + ], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false } \ No newline at end of file diff --git a/NEG/UI/UnityUi/Editor/OverridableNavigationDrawer.cs b/NEG/UI/UnityUi/Editor/OverridableNavigationDrawer.cs index 4f47a96..a0e2de1 100644 --- a/NEG/UI/UnityUi/Editor/OverridableNavigationDrawer.cs +++ b/NEG/UI/UnityUi/Editor/OverridableNavigationDrawer.cs @@ -6,13 +6,12 @@ using UnityEngine; using UnityEngine.UI; using UnityEngine.UIElements; using ObjectField = UnityEditor.Search.ObjectField; - using Toggle = UnityEngine.UIElements.Toggle; namespace NEG.UI.UnityUi.Editor { [CustomPropertyDrawer(typeof(OverridableNavigation))] - public class OverridableNavigationDrawer: PropertyDrawer + public class OverridableNavigationDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { @@ -30,8 +29,10 @@ namespace NEG.UI.UnityUi.Editor var unitRect = new Rect(position.x + 35, position.y, 200, position.height); // Draw fields - pass GUIContent.none to each so they are drawn without labels - EditorGUI.PropertyField(amountRect, property.FindAutoPropertyRelative(nameof(OverridableNavigation.Override)), GUIContent.none); - EditorGUI.PropertyField(unitRect, property.FindAutoPropertyRelative(nameof(OverridableNavigation.Selectable)), GUIContent.none); + EditorGUI.PropertyField(amountRect, + property.FindAutoPropertyRelative(nameof(OverridableNavigation.Override)), GUIContent.none); + EditorGUI.PropertyField(unitRect, + property.FindAutoPropertyRelative(nameof(OverridableNavigation.Selectable)), GUIContent.none); // Set indent back to what it was EditorGUI.indentLevel = indent; @@ -41,7 +42,7 @@ namespace NEG.UI.UnityUi.Editor public override VisualElement CreatePropertyGUI(SerializedProperty property) { - var container = new VisualElement() + var container = new VisualElement { style = { @@ -53,12 +54,9 @@ namespace NEG.UI.UnityUi.Editor }; string name = property.name; - if (name.Length > 0) - { - name = $"{char.ToUpper(name[0])}{name[1..]}"; - } + if (name.Length > 0) name = $"{char.ToUpper(name[0])}{name[1..]}"; - var innerContainer = new VisualElement() + var innerContainer = new VisualElement { style = { @@ -73,20 +71,14 @@ namespace NEG.UI.UnityUi.Editor var enabler = new Toggle(); enabler.BindProperty(property.FindPropertyRelative("k__BackingField")); - - var field = new ObjectField() - { - style = - { - flexGrow = 100 - } - }; + + var field = new ObjectField { style = { flexGrow = 100 } }; var selectableField = property.FindAutoPropertyRelative(nameof(OverridableNavigation.Selectable)); field.BindProperty(selectableField); field.objectType = typeof(Selectable); - + innerContainer.Add(label); innerContainer.Add(enabler); @@ -97,17 +89,17 @@ namespace NEG.UI.UnityUi.Editor { var panel = container.panel; var size = panel.visualTree.contentRect.size; - + // magic value measured with ruler, may change in the future! field.style.maxWidth = size.x * 0.55f + 15; }); - + field.SetEnabled(enabler.value); enabler.RegisterValueChangedCallback(v => { field.SetEnabled(v.newValue); }); - + return container; } } diff --git a/NEG/UI/UnityUi/MonoController.cs b/NEG/UI/UnityUi/MonoController.cs index e6c9a7b..85c5d43 100644 --- a/NEG/UI/UnityUi/MonoController.cs +++ b/NEG/UI/UnityUi/MonoController.cs @@ -1,32 +1,30 @@ using KBCore.Refs; using NEG.UI.UnityUi.Window; using NegUtils.NEG.UI; -using System; using UnityEngine; namespace NEG.UI.UnityUi { public abstract class MonoController : MonoBehaviour, IController { - public IControllable Controllable => controllable.Value; + [SerializeField] [Self] protected InterfaceRef controllable; - [SerializeField, Self] protected InterfaceRef controllable; - protected MonoWindow ControllableAsWindow => (MonoWindow)controllable.Value; - + protected virtual void Awake() { controllable.Value.OnOpened += OnOpened; controllable.Value.OnClosed += OnClosed; controllable.Value.OnBackUsed += OnBackUsed; } - + private void OnValidate() => this.ValidateRefs(); - + public IControllable Controllable => controllable.Value; + protected virtual void OnOpened(object data) { } protected virtual void OnClosed() { } - + protected virtual void OnBackUsed(IControllable.BackUsed obj) { } } } \ No newline at end of file diff --git a/NEG/UI/UnityUi/MonoUiInputManger.cs b/NEG/UI/UnityUi/MonoUiInputManger.cs index 4aac796..846c91d 100644 --- a/NEG/UI/UnityUi/MonoUiInputManger.cs +++ b/NEG/UI/UnityUi/MonoUiInputManger.cs @@ -12,16 +12,20 @@ namespace NEG.UI.UnityUi Direction } - public class UiInputModule { public SelectionSource CurrentSelectionSource { get; protected set; }} + public class UiInputModule + { + public SelectionSource CurrentSelectionSource { get; protected set; } + } public class DefaultInputModule : UiInputModule { public DefaultInputModule() { var defaultActions = new DefaultInputActions(); - InputActionReference.Create(defaultActions.UI.Navigate).action.performed += (ctx) => OnSelectionChangeStarted(); + InputActionReference.Create(defaultActions.UI.Navigate).action.performed += + ctx => OnSelectionChangeStarted(); InputActionReference.Create(defaultActions.UI.Cancel).action.performed += - (_) => UiManager.Instance.UseBack(); + _ => UiManager.Instance.UseBack(); defaultActions.Enable(); if (Gamepad.current != null) @@ -35,11 +39,11 @@ namespace NEG.UI.UnityUi //var gamepadAction = new InputAction(binding: "//*"); //gamepadAction.performed += (context) => OnSelectionChangeStarted(); //gamepadAction.Enable(); - + var mouseAction = new InputAction(binding: "//*"); - mouseAction.performed += (context) => + mouseAction.performed += context => { - if(CurrentSelectionSource == SelectionSource.Pointer) + if (CurrentSelectionSource == SelectionSource.Pointer) return; SetPointerInput(); }; @@ -48,35 +52,32 @@ namespace NEG.UI.UnityUi private void OnSelectionChangeStarted() { - if(CurrentSelectionSource == SelectionSource.Direction && EventSystem.current.currentSelectedGameObject != null) + if (CurrentSelectionSource == SelectionSource.Direction && + EventSystem.current.currentSelectedGameObject != null) return; SetDirectionInput(); } private void SetDirectionInput() { - if (EventSystem.current == null || MonoUiManager.Instance == null ) - { - return; - } + if (EventSystem.current == null || MonoUiManager.Instance == null) return; CurrentSelectionSource = SelectionSource.Direction; Cursor.visible = false; - if (EventSystem.current.currentSelectedGameObject == null && MonoUiManager.Instance.CurrentMainWindow != null) + if (EventSystem.current.currentSelectedGameObject == null && + MonoUiManager.Instance.CurrentMainWindow != null) { - EventSystem.current.SetSelectedGameObject(((MonoWindow)MonoUiManager.Instance.CurrentMainWindow).DefaultSelectedItem); + EventSystem.current.SetSelectedGameObject(((MonoWindow)MonoUiManager.Instance.CurrentMainWindow) + .DefaultSelectedItem); return; } + var data = new PointerEventData(EventSystem.current); var currentSelected = EventSystem.current.currentSelectedGameObject; if (currentSelected != null) - { for (var current = EventSystem.current.currentSelectedGameObject.transform; current != null; current = current.parent) - { ExecuteEvents.Execute(current.gameObject, data, ExecuteEvents.pointerExitHandler); - } - } EventSystem.current.SetSelectedGameObject(currentSelected); } @@ -92,23 +93,21 @@ namespace NEG.UI.UnityUi return; } - if (EventSystem.current.currentInputModule == null) + if (EventSystem.current.currentInputModule == null) return; - + EventSystem.current.SetSelectedGameObject(null); - + var module = (InputSystemUIInputModule)EventSystem.current.currentInputModule; var result = module.GetLastRaycastResult(0); - if(result.gameObject == null) + if (result.gameObject == null) return; - + var data = new PointerEventData(EventSystem.current); for (var current = result.gameObject.transform; current != null; current = current.parent) - { ExecuteEvents.Execute(current.gameObject, data, ExecuteEvents.pointerEnterHandler); - } } } } \ No newline at end of file diff --git a/NEG/UI/UnityUi/MonoUiManager.cs b/NEG/UI/UnityUi/MonoUiManager.cs index dbafda8..a3e7fb5 100644 --- a/NEG/UI/UnityUi/MonoUiManager.cs +++ b/NEG/UI/UnityUi/MonoUiManager.cs @@ -6,7 +6,6 @@ using NEG.UI.UnityUi.Popup; using NEG.UI.UnityUi.Window; using NEG.Utils; using System; -using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; using UnityEngine.EventSystems; @@ -16,43 +15,42 @@ using Object = UnityEngine.Object; namespace NEG.UI.UnityUi { /// - /// Implements ui using UnityUI and Unity Event System with New Input System. - /// You have to provide prefabs within resources: - /// - UI/PopupCanvas - prefab with canvas to create popups (will be created on every scene) - /// - UI/DefaultPopupPrefab - prefab of default popup with 2 options (has to have component) - /// NEG_UI_DISABLE_WARNING_DEFAULT_SELECTION + /// Implements ui using UnityUI and Unity Event System with New Input System. + /// You have to provide prefabs within resources: + /// - UI/PopupCanvas - prefab with canvas to create popups (will be created on every scene) + /// + /// - UI/DefaultPopupPrefab - prefab of default popup with 2 options (has to have + /// component) + /// + /// NEG_UI_DISABLE_WARNING_DEFAULT_SELECTION /// public class MonoUiManager : UiManager, IDisposable { - //TODO: use default unity selection - //TODO: window snaping to slots - public static new MonoUiManager Instance { get; private set; } - - public ButtonSettings DefaultUiSettings { get; } - public KeyBasedFactory BehavioursFactory { get; private set; } - - //TODO: editor to auto add slots, buttons - - private readonly MonoDefaultPopup defaultPopupPrefab; private readonly GameObject canvasPrefab; - private UiInputModule inputModule; + //TODO: editor to auto add slots, buttons + + private readonly MonoDefaultPopup defaultPopupPrefab; + + private readonly UiInputModule inputModule; public MonoUiManager(IArea startArea, Type inputModuleType, ButtonSettings defaultUiSettings) : base(startArea) { Instance = this; - + var popupCanvas = Resources.Load("UI/PopupCanvas"); var defaultPopup = Resources.Load("UI/DefaultPopupPrefab"); - - Assert.IsNotNull(popupCanvas,"No canvas prefab was provided. Please check MonoUiManager class documentation"); - Assert.IsNotNull(defaultPopup,"No popup prefab was provided. Please check MonoUiManager class documentation"); + + Assert.IsNotNull(popupCanvas, + "No canvas prefab was provided. Please check MonoUiManager class documentation"); + Assert.IsNotNull(defaultPopup, + "No popup prefab was provided. Please check MonoUiManager class documentation"); Assert.IsNotNull(popupCanvas.GetComponent()); Assert.IsNotNull(defaultPopup.GetComponent()); canvasPrefab = popupCanvas; defaultPopupPrefab = defaultPopup.GetComponent(); - + SpawnDefaultPopup(); SceneManager.activeSceneChanged += (_, _) => SpawnDefaultPopup(); @@ -64,6 +62,13 @@ namespace NEG.UI.UnityUi DefaultUiSettings = defaultUiSettings; } + //TODO: use default unity selection + //TODO: window snaping to slots + public static new MonoUiManager Instance { get; private set; } + + public ButtonSettings DefaultUiSettings { get; } + public KeyBasedFactory BehavioursFactory { get; } + public override void Dispose() { base.Dispose(); @@ -73,12 +78,13 @@ namespace NEG.UI.UnityUi protected override void UpdatePopupsState(bool forceShow, int priority = 0, PopupData data = null) { base.UpdatePopupsState(forceShow, priority, data); - if(inputModule.CurrentSelectionSource != SelectionSource.Direction) + if (inputModule.CurrentSelectionSource != SelectionSource.Direction) return; - - if (CurrentPopup == null && (EventSystem.current.currentSelectedGameObject == null || !EventSystem.current.currentSelectedGameObject.activeInHierarchy)) + + if (CurrentPopup == null && (EventSystem.current.currentSelectedGameObject == null || + !EventSystem.current.currentSelectedGameObject.activeInHierarchy)) { - if(((MonoWindow)CurrentMainWindow).DefaultSelectedItem == null) + if (((MonoWindow)CurrentMainWindow).DefaultSelectedItem == null) return; EventSystem.current.SetSelectedGameObject(((MonoWindow)CurrentMainWindow).DefaultSelectedItem); } diff --git a/NEG/UI/UnityUi/NEG.UI.UnityUi.asmdef b/NEG/UI/UnityUi/NEG.UI.UnityUi.asmdef index 04c2930..674be13 100644 --- a/NEG/UI/UnityUi/NEG.UI.UnityUi.asmdef +++ b/NEG/UI/UnityUi/NEG.UI.UnityUi.asmdef @@ -1,25 +1,25 @@ { - "name": "NEG.UI.UnityUi", - "rootNamespace": "", - "references": [ - "GUID:343deaaf83e0cee4ca978e7df0b80d21", - "GUID:7361f1d9c43da6649923760766194746", - "GUID:6055be8ebefd69e48b49212b09b47b2f", - "GUID:23eed6c2401dca1419d1ebd180e58c5a", - "GUID:33759803a11f4d538227861a78aba30b", - "GUID:0c752da273b17c547ae705acf0f2adf2", - "GUID:3c4294719a93e3c4e831a9ff0c261e8a", - "GUID:75469ad4d38634e559750d17036d5f7c" - ], - "includePlatforms": [], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": false, - "precompiledReferences": [ - "" - ], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false + "name": "NEG.UI.UnityUi", + "rootNamespace": "", + "references": [ + "GUID:343deaaf83e0cee4ca978e7df0b80d21", + "GUID:7361f1d9c43da6649923760766194746", + "GUID:6055be8ebefd69e48b49212b09b47b2f", + "GUID:23eed6c2401dca1419d1ebd180e58c5a", + "GUID:33759803a11f4d538227861a78aba30b", + "GUID:0c752da273b17c547ae705acf0f2adf2", + "GUID:3c4294719a93e3c4e831a9ff0c261e8a", + "GUID:75469ad4d38634e559750d17036d5f7c" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [ + "" + ], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false } \ No newline at end of file diff --git a/NEG/UI/UnityUi/Popup/MonoDefaultPopup.cs b/NEG/UI/UnityUi/Popup/MonoDefaultPopup.cs index e265243..ea01c70 100644 --- a/NEG/UI/UnityUi/Popup/MonoDefaultPopup.cs +++ b/NEG/UI/UnityUi/Popup/MonoDefaultPopup.cs @@ -16,14 +16,11 @@ namespace NEG.UI.UnityUi.Popup public void SetContent(string title, string content, List<(string, Action)> options) { - foreach (Transform child in buttonsParent) - { - Destroy(child.gameObject); - } + foreach (Transform child in buttonsParent) Destroy(child.gameObject); titleText.text = title; contentText.text = content; - + foreach ((string text, Action action) item in options) { var button = Instantiate(buttonPrefab, buttonsParent); diff --git a/NEG/UI/UnityUi/Popup/MonoPopup.cs b/NEG/UI/UnityUi/Popup/MonoPopup.cs index 2a7a2a3..74c2c3a 100644 --- a/NEG/UI/UnityUi/Popup/MonoPopup.cs +++ b/NEG/UI/UnityUi/Popup/MonoPopup.cs @@ -6,9 +6,8 @@ namespace NEG.UI.UnityUi.Popup { public class MonoPopup : MonoBehaviour, IPopup { - public event Action OnPopupClosed; - protected PopupData data; + public event Action OnPopupClosed; public virtual void Show(PopupData data) { @@ -19,12 +18,11 @@ namespace NEG.UI.UnityUi.Popup public virtual void Close(bool silent = false) { gameObject.SetActive(false); - - if(silent) + + if (silent) return; - + OnPopupClosed?.Invoke(data); } - } } \ No newline at end of file diff --git a/NEG/UI/UnityUi/Window/CloseWindowOnBack.cs b/NEG/UI/UnityUi/Window/CloseWindowOnBack.cs index 29b0893..ca8ccde 100644 --- a/NEG/UI/UnityUi/Window/CloseWindowOnBack.cs +++ b/NEG/UI/UnityUi/Window/CloseWindowOnBack.cs @@ -7,7 +7,7 @@ namespace NEG.UI.UnityUi.Window { public class CloseWindowOnBack : MonoController { - [SerializeField, Self(Flag.Editable)] private MonoWindow window; + [SerializeField] [Self(Flag.Editable)] private MonoWindow window; protected override void OnBackUsed(IControllable.BackUsed backUsed) { diff --git a/NEG/UI/UnityUi/Window/MonoWindow.cs b/NEG/UI/UnityUi/Window/MonoWindow.cs index 6536f7c..7597334 100644 --- a/NEG/UI/UnityUi/Window/MonoWindow.cs +++ b/NEG/UI/UnityUi/Window/MonoWindow.cs @@ -1,6 +1,4 @@ -using NEG.UI.Area; -using NEG.UI.UnityUi.Buttons; -using NEG.UI.UnityUi.WindowSlot; +using NEG.UI.UnityUi.WindowSlot; using NEG.UI.Window; using NEG.UI.WindowSlot; using NegUtils.NEG.UI; @@ -8,31 +6,45 @@ using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; -using UnityEngine.Serialization; namespace NEG.UI.UnityUi.Window { [DefaultExecutionOrder(10)] public class MonoWindow : MonoBehaviour, IWindow { - public event Action OnOpened; - public event Action OnClosed; - public event Action OnBackUsed; - - public IEnumerable AvailableSlots => windowSlots; - public IWindowSlot Parent { get; private set; } - - public bool IsMainWindow { get; private set; } - - public bool IsOpened { get; protected set; } - - private IWindowSlot DefaultWindowSlot => windowSlots[0]; - public GameObject DefaultSelectedItem => defaultSelectedItem; - [SerializeField] private List windowSlots; [SerializeField] private GameObject defaultSelectedItem; + public bool IsMainWindow { get; } + + public bool IsOpened { get; protected set; } + + private IWindowSlot DefaultWindowSlot => windowSlots[0]; + public GameObject DefaultSelectedItem => defaultSelectedItem; + + private void Awake() => ((IWindow)this).SetHiddenState(); + + private void OnDestroy() + { + if (IsOpened) UiManager.Instance.OnWindowClosed(this); + } + + private void OnValidate() + { +#if !NEG_UI_DISABLE_WARNING_DEFAULT_SELECTION + if (defaultSelectedItem == null) + Debug.LogWarning($"Window {name} should have default selected item set"); +#endif + } + + public event Action OnOpened; + public event Action OnClosed; + public event Action OnBackUsed; + + public IEnumerable AvailableSlots => windowSlots; + public IWindowSlot Parent { get; private set; } + public void SetOpenedState(IWindowSlot parentSlot, object data) { gameObject.SetActive(true); @@ -58,28 +70,10 @@ namespace NEG.UI.UnityUi.Window public void SeVisibleState() => gameObject.SetActive(true); - private void Awake() => ((IWindow)this).SetHiddenState(); - - private void OnDestroy() - { - if (IsOpened) - { - UiManager.Instance.OnWindowClosed(this); - } - } - - private void OnValidate() - { - #if !NEG_UI_DISABLE_WARNING_DEFAULT_SELECTION - if(defaultSelectedItem == null) - Debug.LogWarning($"Window {name} should have default selected item set"); - #endif - } - public void OpenWindow(IWindow window, object data = null) => DefaultWindowSlot.AttachWindow(window, data); - public void SetDefaultSelectedItem(GameObject item) => defaultSelectedItem = item; - public void TryUseBack(ref IControllable.BackUsed backUsed) => OnBackUsed?.Invoke(backUsed); + + public void SetDefaultSelectedItem(GameObject item) => defaultSelectedItem = item; } } \ No newline at end of file diff --git a/NEG/UI/UnityUi/WindowSlot/MonoWindowSlot.cs b/NEG/UI/UnityUi/WindowSlot/MonoWindowSlot.cs index 90fb9cf..a9400f6 100644 --- a/NEG/UI/UnityUi/WindowSlot/MonoWindowSlot.cs +++ b/NEG/UI/UnityUi/WindowSlot/MonoWindowSlot.cs @@ -1,22 +1,18 @@ -using KBCore.Refs; -using NEG.UI.Area; -using NEG.UI.Window; +using NEG.UI.Window; using NEG.UI.WindowSlot; -using System; -using UnityEngine; using TNRD; +using UnityEngine; namespace NEG.UI.UnityUi.WindowSlot { public abstract class MonoWindowSlot : MonoBehaviour, IWindowSlot { + [SerializeField] private SerializableInterface slotsHolder; [field: SerializeField] public bool OpenWindowAsMain { get; private set; } - + public ISlotsHolder ParentHolder => slotsHolder.Value; public abstract void AttachWindow(IWindow window, object data); public abstract void DetachWindow(IWindow window); public abstract void CloseAllWindows(); - - [SerializeField] private SerializableInterface slotsHolder; } } \ No newline at end of file diff --git a/NEG/UI/UnityUi/WindowSlot/SingleWindowSlot.cs b/NEG/UI/UnityUi/WindowSlot/SingleWindowSlot.cs index 9fff830..8d2659d 100644 --- a/NEG/UI/UnityUi/WindowSlot/SingleWindowSlot.cs +++ b/NEG/UI/UnityUi/WindowSlot/SingleWindowSlot.cs @@ -1,11 +1,12 @@ using NEG.UI.UnityUi.WindowSlot; using NEG.UI.Window; -using UnityEngine; namespace NEG.UI.WindowSlot { public class SingleWindowSlot : MonoWindowSlot { + private IWindow currentWindow; + public IWindow CurrentWindow { get => currentWindow; @@ -15,9 +16,7 @@ namespace NEG.UI.WindowSlot currentWindow = value; } } - - private IWindow currentWindow; - + public override void AttachWindow(IWindow window, object data) { CurrentWindow = window; @@ -26,7 +25,7 @@ namespace NEG.UI.WindowSlot public override void DetachWindow(IWindow window) { - if(UiManager.Instance.CurrentMainWindow == window) + if (UiManager.Instance.CurrentMainWindow == window) UiManager.Instance.MainWindowClosed(window); CurrentWindow = null; } diff --git a/NEG/UI/UnityUi/WindowSlot/SingleWindowSlotWithHistory.cs b/NEG/UI/UnityUi/WindowSlot/SingleWindowSlotWithHistory.cs index fc3390c..f92c860 100644 --- a/NEG/UI/UnityUi/WindowSlot/SingleWindowSlotWithHistory.cs +++ b/NEG/UI/UnityUi/WindowSlot/SingleWindowSlotWithHistory.cs @@ -3,13 +3,16 @@ using NEG.UI.UnityUi.Window; using NEG.UI.UnityUi.WindowSlot; using NEG.UI.Window; using System.Collections.Generic; -using System.Linq; using UnityEngine.EventSystems; namespace NegUtils.NEG.UI.UnityUi.WindowSlot { public class SingleWindowSlotWithHistory : MonoWindowSlot { + private readonly List windowsHistory = new(); + + private IWindow currentWindow; + public IWindow CurrentWindow { get => currentWindow; @@ -20,16 +23,12 @@ namespace NegUtils.NEG.UI.UnityUi.WindowSlot CloseAllWindows(); return; } - + currentWindow?.SetHiddenState(); currentWindow = value; windowsHistory.Add(currentWindow); } } - - private IWindow currentWindow; - - private readonly List windowsHistory = new List(); public override void AttachWindow(IWindow window, object data) { @@ -39,24 +38,22 @@ namespace NegUtils.NEG.UI.UnityUi.WindowSlot public override void DetachWindow(IWindow window) { - if(window == null) + if (window == null) return; window.SetClosedState(); windowsHistory.Remove(window); if (window != currentWindow || windowsHistory.Count == 0) return; currentWindow = windowsHistory[^1]; currentWindow.SeVisibleState(); - if(UiManager.Instance.CurrentMainWindow == window) + if (UiManager.Instance.CurrentMainWindow == window) UiManager.Instance.MainWindowClosed(window); EventSystem.current.SetSelectedGameObject(((MonoWindow)currentWindow).DefaultSelectedItem); } + public override void CloseAllWindows() { currentWindow = null; - foreach (var window in windowsHistory) - { - window.SetClosedState(); - } + foreach (var window in windowsHistory) window.SetClosedState(); windowsHistory.Clear(); } } diff --git a/NEG/UI/Window/IWindow.cs b/NEG/UI/Window/IWindow.cs index e470343..a6cceb5 100644 --- a/NEG/UI/Window/IWindow.cs +++ b/NEG/UI/Window/IWindow.cs @@ -1,5 +1,4 @@ -using JetBrains.Annotations; -using NEG.UI.Area; +using NEG.UI.Area; using NEG.UI.WindowSlot; using NegUtils.NEG.UI; using UnityEngine; @@ -9,29 +8,29 @@ namespace NEG.UI.Window public interface IWindow : ISlotsHolder, IControllable { /// - /// Parent slot of this window. + /// Parent slot of this window. /// IWindowSlot Parent { get; } /// - /// Called internally by slot to open window. + /// Called internally by slot to open window. /// /// slot that opens window /// data void SetOpenedState(IWindowSlot parentSlot, object data); /// - /// Called internally to close window by slot. + /// Called internally to close window by slot. /// void SetClosedState(); - + /// - /// Called internally to hide window by slot. + /// Called internally to hide window by slot. /// void SetHiddenState(); - + /// - /// Called internally to set window visible by slot. + /// Called internally to set window visible by slot. /// void SeVisibleState(); } @@ -39,7 +38,7 @@ namespace NEG.UI.Window public static class WindowInterfaceExtensions { /// - /// Opens window as slot child. If slot is null or not provided, as child of current area. + /// Opens window as slot child. If slot is null or not provided, as child of current area. /// /// window to open /// slot to attach window @@ -54,17 +53,17 @@ namespace NEG.UI.Window UiManager.Instance.CurrentArea.OpenWindow(window, data); } - + /// - /// Opens window as child of selected area. + /// Opens window as child of selected area. /// /// window to open /// area to attach window /// data to send to window public static void Open(this IWindow window, IArea area, object data = null) => area.OpenWindow(window, data); - + /// - /// Open passed window as child of this window. + /// Open passed window as child of this window. /// /// parent window /// window to open @@ -73,14 +72,16 @@ namespace NEG.UI.Window { if (windowToOpen == null) { - Debug.LogError($"Window to open cannot be null"); + Debug.LogError("Window to open cannot be null"); return; } + window.OpenWindow(windowToOpen, data); } - + /// - /// Open window as child of provided window. If is null, as child of current main window in . If there is no main window, open on current area. + /// Open window as child of provided window. If is null, as child of current main + /// window in . If there is no main window, open on current area. /// /// window to open /// parent window @@ -101,9 +102,9 @@ namespace NEG.UI.Window UiManager.Instance.CurrentArea.OpenWindow(window, data); } - + /// - /// Close window. + /// Close window. /// /// window to close public static void Close(this IWindow window) => window.Parent.DetachWindow(window); diff --git a/NEG/UI/WindowSlot/ISlotsHolder.cs b/NEG/UI/WindowSlot/ISlotsHolder.cs index f3740a9..5383716 100644 --- a/NEG/UI/WindowSlot/ISlotsHolder.cs +++ b/NEG/UI/WindowSlot/ISlotsHolder.cs @@ -8,7 +8,7 @@ namespace NEG.UI.WindowSlot IEnumerable AvailableSlots { get; } /// - /// Open window + /// Open window /// /// /// @@ -16,10 +16,7 @@ namespace NEG.UI.WindowSlot void CloseAllWindows() { - foreach (var slot in AvailableSlots) - { - slot.CloseAllWindows(); - } + foreach (var slot in AvailableSlots) slot.CloseAllWindows(); } } } \ No newline at end of file diff --git a/NEG/UI/WindowSlot/IWindowSlot.cs b/NEG/UI/WindowSlot/IWindowSlot.cs index 8b06bbd..b2b493e 100644 --- a/NEG/UI/WindowSlot/IWindowSlot.cs +++ b/NEG/UI/WindowSlot/IWindowSlot.cs @@ -1,5 +1,4 @@ -using NEG.UI.Area; -using NEG.UI.Window; +using NEG.UI.Window; namespace NEG.UI.WindowSlot { diff --git a/RequireInterfaceAttribute.cs b/RequireInterfaceAttribute.cs index 21d71d8..ff7e4ba 100644 --- a/RequireInterfaceAttribute.cs +++ b/RequireInterfaceAttribute.cs @@ -1,4 +1,6 @@ +using System; using UnityEngine; + /// /// Attribute that require implementation of the provided interface. /// @@ -7,15 +9,16 @@ namespace NEG.Utils { public class RequireInterfaceAttribute : PropertyAttribute { - // Interface type. - public System.Type requiredType { get; private set; } /// - /// Requiring implementation of the interface. + /// Requiring implementation of the interface. /// /// Interface type. - public RequireInterfaceAttribute(System.Type type) + public RequireInterfaceAttribute(Type type) { requiredType = type; } + + // Interface type. + public Type requiredType { get; private set; } } } \ No newline at end of file diff --git a/Timing/AutoTimeMachine.cs b/Timing/AutoTimeMachine.cs index c12e93e..e8df30e 100644 --- a/Timing/AutoTimeMachine.cs +++ b/Timing/AutoTimeMachine.cs @@ -5,33 +5,28 @@ namespace NEG.Utils.Timing { public class AutoTimeMachine { - [PublicAPI] - public double Interval { get; set; } - - [PublicAPI] - public Action Action { get; } - private readonly TimeMachine machine; - - public AutoTimeMachine(Action action, double interval) + + public AutoTimeMachine(Action action, double interval) { Action = action; Interval = interval; machine = new TimeMachine(); } + [PublicAPI] public double Interval { get; set; } + + [PublicAPI] public Action Action { get; } + /// - /// Forwards the time by given amount, triggers assigned action relevant amount of times + /// Forwards the time by given amount, triggers assigned action relevant amount of times /// /// Amount of time to forward by public void Forward(double time) { machine.Accumulate(time); int rolls = machine.RetrieveAll(Interval); - for (int i = 0; i < rolls; i++) - { - Action(); - } + for (int i = 0; i < rolls; i++) Action(); } } -} +} \ No newline at end of file diff --git a/Timing/TimeMachine.cs b/Timing/TimeMachine.cs index 2784213..ebbe6f2 100644 --- a/Timing/TimeMachine.cs +++ b/Timing/TimeMachine.cs @@ -13,44 +13,47 @@ namespace NEG.Utils.Timing } /// - /// Adds time into the TimeMachine + /// Adds time into the TimeMachine /// /// Amount of time to be added public void Accumulate(double time) => timeInternal += time; /// - /// Retrieves given amount of time from the TimeMachine + /// Retrieves given amount of time from the TimeMachine /// /// /// Amount of time retrieved - public double Retrieve(double maxTime) + public double Retrieve(double maxTime) { - if(!double.IsFinite(maxTime)) + if (!double.IsFinite(maxTime)) { double timeRetrieved = timeInternal; timeInternal = 0; return timeRetrieved; } + double timeLeft = timeInternal - maxTime; timeInternal = Math.Max(timeLeft, 0); return Math.Min(maxTime + timeLeft, maxTime); } /// - /// Attempts to retrieves given amount of time from the TimeMachine
- /// If there is enough accumulated in this machine subtracts that amount and returns true, otherwise returns false + /// Attempts to retrieves given amount of time from the TimeMachine
+ /// If there is enough accumulated in this machine subtracts that amount and returns true, + /// otherwise returns false ///
/// public bool TryRetrieve(double time) { - if (!(timeInternal >= time)) + if (!(timeInternal >= time)) return false; timeInternal -= time; return true; } /// - /// Result is equivalent to calling as many times as possible, but is faster for larger values + /// Result is equivalent to calling as many times as possible, but is faster for + /// larger values /// /// Single unit of warp time, must be positive /// Maximum amount of warps, must be positive @@ -63,4 +66,4 @@ namespace NEG.Utils.Timing return result; } } -} +} \ No newline at end of file diff --git a/UiToolkit/MultiSelectChips/IMultiSelectChipItem.cs b/UiToolkit/MultiSelectChips/IMultiSelectChipItem.cs index d2c3b0f..dd8d642 100644 --- a/UiToolkit/MultiSelectChips/IMultiSelectChipItem.cs +++ b/UiToolkit/MultiSelectChips/IMultiSelectChipItem.cs @@ -1,5 +1,4 @@ -using System.Collections; -using UnityEngine; +using UnityEngine; namespace NEG.Utils.UiToolkits { diff --git a/UiToolkit/MultiSelectChips/MultiSelectChipItem.cs b/UiToolkit/MultiSelectChips/MultiSelectChipItem.cs index 74dd601..6016373 100644 --- a/UiToolkit/MultiSelectChips/MultiSelectChipItem.cs +++ b/UiToolkit/MultiSelectChips/MultiSelectChipItem.cs @@ -4,13 +4,11 @@ namespace NEG.Utils.UiToolkits { public class MultiSelectChipItem { - public VisualElement VisualElement { get; } - public IMultiSelectChipItem ChipItem { get; } - private readonly MultiSelectChips parent; - public MultiSelectChipItem(VisualElement visualElement, IMultiSelectChipItem element, MultiSelectChips multiSelectChips) - { + public MultiSelectChipItem(VisualElement visualElement, IMultiSelectChipItem element, + MultiSelectChips multiSelectChips) + { VisualElement = visualElement; ChipItem = element; parent = multiSelectChips; @@ -18,5 +16,8 @@ namespace NEG.Utils.UiToolkits visualElement.Q("Color").style.backgroundColor = element.Color; visualElement.Q