Code cleanup

This commit is contained in:
Hubert Mattusch 2024-02-12 21:26:24 +01:00
parent ae89122e42
commit e819020474
73 changed files with 857 additions and 939 deletions

View File

@ -1,5 +1,4 @@
using UnityEngine; using UnityEngine;
using UnityEngine.SceneManagement;
namespace NEG.Utils namespace NEG.Utils
{ {
@ -10,4 +9,3 @@ namespace NEG.Utils
#endif #endif
} }
} }

View File

@ -5,7 +5,8 @@ namespace NEG.Utils.Collections
public static class DictionaryExtensions public static class DictionaryExtensions
{ {
/// <summary> /// <summary>
/// Adds given value to a dictionary if there was no element at given <paramref name="key"/>, replaces element with <paramref name="value"> otherwise. /// Adds given value to a dictionary if there was no element at given <paramref name="key" />, replaces element with
/// <paramref name="value"> otherwise.
/// </summary> /// </summary>
/// <returns>true if element was added, false if it was replaced</returns> /// <returns>true if element was added, false if it was replaced</returns>
public static bool AddOrUpdate<K, V>(this Dictionary<K, V> dict, K key, V value) public static bool AddOrUpdate<K, V>(this Dictionary<K, V> dict, K key, V value)
@ -15,24 +16,20 @@ namespace NEG.Utils.Collections
dict[key] = value; dict[key] = value;
return false; return false;
} }
else
{
dict.Add(key, value); dict.Add(key, value);
return true; return true;
} }
}
/// <summary> /// <summary>
/// Gets a value from the dictionary under a specified key or adds it if did not exist and returns <paramref name="defaultValue"/>. /// Gets a value from the dictionary under a specified key or adds it if did not exist and returns
/// <paramref name="defaultValue" />.
/// </summary> /// </summary>
/// <returns>value under a given <paramref name="key" /> if it exists, <paramref name="defaultValue" /> otherwise</returns> /// <returns>value under a given <paramref name="key" /> if it exists, <paramref name="defaultValue" /> otherwise</returns>
public static V GetOrSetToDefault<K, V>(this Dictionary<K, V> dict, K key, V defaultValue) public static V GetOrSetToDefault<K, V>(this Dictionary<K, V> dict, K key, V defaultValue)
{ {
if (dict.TryGetValue(key, out V value)) if (dict.TryGetValue(key, out var value)) return value;
{
return value;
}
dict.Add(key, defaultValue); dict.Add(key, defaultValue);
return defaultValue; return defaultValue;

View File

@ -6,20 +6,15 @@ namespace NEG.Utils
{ {
public static class CoroutineUtils public static class CoroutineUtils
{ {
private static readonly WaitForEndOfFrame WaitForEndOfFrame = new WaitForEndOfFrame(); private static readonly WaitForEndOfFrame WaitForEndOfFrame = new();
public static IEnumerator WaitForFrames(int count) public static IEnumerator WaitForFrames(int count)
{ {
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++) yield return null;
{
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)); mono.StartCoroutine(ActionAfterFrames(count, action));
}
public static IEnumerator ActionAfterFrames(int count, Action action) public static IEnumerator ActionAfterFrames(int count, Action action)
{ {
@ -27,20 +22,26 @@ namespace NEG.Utils
action?.Invoke(); 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) public static IEnumerator ActionAfterEndOfFrame(Action action)
{ {
yield return WaitForEndOfFrame; yield return WaitForEndOfFrame;
action?.Invoke(); 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) public static IEnumerator ActionAtNextFrame(Action action)
{ {
yield return null; yield return null;
action?.Invoke(); 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) public static IEnumerator ActionAfterTime(float time, Action action)
{ {

View File

@ -1,8 +1,8 @@
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using UnityEngine;
using UnityEditor; using UnityEditor;
using UnityEditor.Build.Player; using UnityEditor.Build;
using UnityEngine;
using Debug = UnityEngine.Debug; using Debug = UnityEngine.Debug;
public static class BuildingUtils public static class BuildingUtils
@ -12,9 +12,9 @@ public static class BuildingUtils
[MenuItem("Tools/PrepareForBuild", priority = -10)] [MenuItem("Tools/PrepareForBuild", priority = -10)]
public static void PrepareForBuild() public static void PrepareForBuild()
{ {
var namedBuildTarget = UnityEditor.Build.NamedBuildTarget.FromBuildTargetGroup( var namedBuildTarget = NamedBuildTarget.FromBuildTargetGroup(
BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget)); BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget));
var args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget); string[] args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget);
var argsList = args.ToList(); var argsList = args.ToList();
argsList.Remove(SteamBuildDefine); argsList.Remove(SteamBuildDefine);
PlayerSettings.SetScriptingDefineSymbols(namedBuildTarget, argsList.ToArray()); PlayerSettings.SetScriptingDefineSymbols(namedBuildTarget, argsList.ToArray());
@ -25,9 +25,9 @@ public static class BuildingUtils
{ {
PrepareForBuild(); PrepareForBuild();
var namedBuildTarget = UnityEditor.Build.NamedBuildTarget.FromBuildTargetGroup( var namedBuildTarget = NamedBuildTarget.FromBuildTargetGroup(
BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget)); BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget));
var args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget); string[] args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget);
var argsList = args.ToList(); var argsList = args.ToList();
argsList.Add(SteamBuildDefine); argsList.Add(SteamBuildDefine);
PlayerSettings.SetScriptingDefineSymbols(namedBuildTarget, argsList.ToArray()); PlayerSettings.SetScriptingDefineSymbols(namedBuildTarget, argsList.ToArray());
@ -128,9 +128,7 @@ public static class BuildingUtils
var buildPlayerOptions = new BuildPlayerOptions { scenes = new string[EditorBuildSettings.scenes.Length] }; var buildPlayerOptions = new BuildPlayerOptions { scenes = new string[EditorBuildSettings.scenes.Length] };
for (int i = 0; i < EditorBuildSettings.scenes.Length; i++) for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)
{
buildPlayerOptions.scenes[i] = EditorBuildSettings.scenes[i].path; buildPlayerOptions.scenes[i] = EditorBuildSettings.scenes[i].path;
}
buildPlayerOptions.target = BuildTarget.Android; buildPlayerOptions.target = BuildTarget.Android;
buildPlayerOptions.options = BuildOptions.None; buildPlayerOptions.options = BuildOptions.None;
@ -143,9 +141,7 @@ public static class BuildingUtils
{ {
var buildPlayerOptions = new BuildPlayerOptions { scenes = new string[EditorBuildSettings.scenes.Length] }; var buildPlayerOptions = new BuildPlayerOptions { scenes = new string[EditorBuildSettings.scenes.Length] };
for (int i = 0; i < EditorBuildSettings.scenes.Length; i++) for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)
{
buildPlayerOptions.scenes[i] = EditorBuildSettings.scenes[i].path; buildPlayerOptions.scenes[i] = EditorBuildSettings.scenes[i].path;
}
buildPlayerOptions.extraScriptingDefines = additionalDefines; buildPlayerOptions.extraScriptingDefines = additionalDefines;
@ -160,9 +156,7 @@ public static class BuildingUtils
{ {
var buildPlayerOptions = new BuildPlayerOptions { scenes = new string[EditorBuildSettings.scenes.Length] }; var buildPlayerOptions = new BuildPlayerOptions { scenes = new string[EditorBuildSettings.scenes.Length] };
for (int i = 0; i < EditorBuildSettings.scenes.Length; i++) for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)
{
buildPlayerOptions.scenes[i] = EditorBuildSettings.scenes[i].path; buildPlayerOptions.scenes[i] = EditorBuildSettings.scenes[i].path;
}
buildPlayerOptions.extraScriptingDefines = additionalDefines; buildPlayerOptions.extraScriptingDefines = additionalDefines;
@ -176,26 +170,27 @@ public static class BuildingUtils
private static void IncreaseBuildNumber() private static void IncreaseBuildNumber()
{ {
string[] versionParts = PlayerSettings.bundleVersion.Split('.'); string[] versionParts = PlayerSettings.bundleVersion.Split('.');
if (versionParts.Length != 3 || !int.TryParse(versionParts[2], out int version)) { if (versionParts.Length != 3 || !int.TryParse(versionParts[2], out int version))
{
Debug.LogError("IncreaseBuildNumber failed to update version " + PlayerSettings.bundleVersion); Debug.LogError("IncreaseBuildNumber failed to update version " + PlayerSettings.bundleVersion);
return; return;
} }
versionParts[2] = (version + 1).ToString(); versionParts[2] = (version + 1).ToString();
PlayerSettings.bundleVersion = string.Join(".", versionParts); PlayerSettings.bundleVersion = string.Join(".", versionParts);
} }
private static void UploadSteam(bool demo = false) 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) if (demo)
{ command =
command = $"cd {Application.dataPath}/../../{Application.productName}-Steam/ContentBuilder && push_demo.bat"; $"cd {Application.dataPath}/../../{Application.productName}-Steam/ContentBuilder && push_demo.bat";
}
var processInfo = new ProcessStartInfo("cmd.exe", $"/c {command}") var processInfo = new ProcessStartInfo("cmd.exe", $"/c {command}")
{ {
CreateNoWindow = true, CreateNoWindow = true, UseShellExecute = false
UseShellExecute = false
}; };
var process = Process.Start(processInfo); var process = Process.Start(processInfo);
process.WaitForExit(); process.WaitForExit();
@ -207,15 +202,16 @@ public static class BuildingUtils
{ {
if (CanBuildUtil()) if (CanBuildUtil())
return true; 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; return false;
} }
private static bool CanBuildUtil() private static bool CanBuildUtil()
{ {
var namedBuildTarget = UnityEditor.Build.NamedBuildTarget.FromBuildTargetGroup( var namedBuildTarget = NamedBuildTarget.FromBuildTargetGroup(
BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget)); BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget));
var args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget); string[] args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget);
var argsList = args.ToList(); var argsList = args.ToList();
if (argsList.Contains(SteamBuildDefine)) if (argsList.Contains(SteamBuildDefine))

View File

@ -8,14 +8,19 @@ namespace NEG.Utils.Editor.ComponentsAdditionalItems
{ {
[MenuItem("CONTEXT/CanvasScaler/Full HD horizontal", false, 2000)] [MenuItem("CONTEXT/CanvasScaler/Full HD horizontal", false, 2000)]
public static void SetFullHdHorizontal(MenuCommand command) => SetComponent(command, 1920, 1080); public static void SetFullHdHorizontal(MenuCommand command) => SetComponent(command, 1920, 1080);
[MenuItem("CONTEXT/CanvasScaler/Full HD vertical", false, 2000)] [MenuItem("CONTEXT/CanvasScaler/Full HD vertical", false, 2000)]
public static void SetFullHdVertical(MenuCommand command) => SetComponent(command, 1080, 1920); public static void SetFullHdVertical(MenuCommand command) => SetComponent(command, 1080, 1920);
[MenuItem("CONTEXT/CanvasScaler/Full 2k horizontal", false, 2000)] [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)] [MenuItem("CONTEXT/CanvasScaler/Full 2k vertical", false, 2000)]
public static void Set2KVertical(MenuCommand command) => SetComponent(command, 1440, 2560); public static void Set2KVertical(MenuCommand command) => SetComponent(command, 1440, 2560);
[MenuItem("CONTEXT/CanvasScaler/Full 4k horizontal", false, 2000)] [MenuItem("CONTEXT/CanvasScaler/Full 4k horizontal", false, 2000)]
public static void Set4KHorizontal(MenuCommand command) => SetComponent(command, 3840, 2160); public static void Set4KHorizontal(MenuCommand command) => SetComponent(command, 3840, 2160);
[MenuItem("CONTEXT/CanvasScaler/Full 4k vertical", false, 2000)] [MenuItem("CONTEXT/CanvasScaler/Full 4k vertical", false, 2000)]
public static void Set4KVertical(MenuCommand command) => SetComponent(command, 2160, 3840); public static void Set4KVertical(MenuCommand command) => SetComponent(command, 2160, 3840);

View File

@ -11,31 +11,26 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.IO; using System.IO;
using UnityEngine;
using UnityEditor; using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;
namespace TheGamedevGuru namespace TheGamedevGuru
{ {
public class EditorInstanceCreator : EditorWindow public class EditorInstanceCreator : EditorWindow
{ {
string _projectInstanceName; private string _extraSubdirectories;
string _extraSubdirectories; private bool _includeProjectSettings = true;
bool _includeProjectSettings = true; private string _projectInstanceName;
[MenuItem("Window/The Gamedev Guru/Editor Instance Creator")] private void OnGUI()
static void Init()
{
((EditorInstanceCreator)EditorWindow.GetWindow(typeof(EditorInstanceCreator))).Show();
}
void OnGUI()
{ {
if (string.IsNullOrEmpty(_projectInstanceName)) if (string.IsNullOrEmpty(_projectInstanceName))
{
_projectInstanceName = PlayerSettings.productName + "_Slave_1"; _projectInstanceName = PlayerSettings.productName + "_Slave_1";
}
EditorGUILayout.Separator(); EditorGUILayout.Separator();
EditorGUILayout.LabelField("The Gamedev Guru - Project Instance Creator"); EditorGUILayout.LabelField("The Gamedev Guru - Project Instance Creator");
@ -53,19 +48,20 @@ namespace TheGamedevGuru
EditorGUILayout.Separator(); EditorGUILayout.Separator();
if (GUILayout.Button("Create")) if (GUILayout.Button("Create"))
{
CreateProjectInstance(_projectInstanceName, _includeProjectSettings, _extraSubdirectories); CreateProjectInstance(_projectInstanceName, _includeProjectSettings, _extraSubdirectories);
}
if (GUILayout.Button("Help")) if (GUILayout.Button("Help"))
{
Application.OpenURL("https://thegamedev.guru/multiple-unity-editor-instances-within-a-single-project/"); 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); Debug.Log(targetDirectory);
if (Directory.Exists(targetDirectory)) if (Directory.Exists(targetDirectory))
{ {
@ -75,29 +71,21 @@ namespace TheGamedevGuru
Directory.CreateDirectory(targetDirectory); Directory.CreateDirectory(targetDirectory);
List<string> subdirectories = new List<string>{"Assets", "Packages"}; var subdirectories = new List<string> { "Assets", "Packages" };
if (includeProjectSettings) if (includeProjectSettings) subdirectories.Add("ProjectSettings");
{
subdirectories.Add("ProjectSettings");
}
foreach (var extraSubdirectory in extraSubdirectories.Split(',')) foreach (string extraSubdirectory in extraSubdirectories.Split(','))
{
subdirectories.Add(extraSubdirectory.Trim()); subdirectories.Add(extraSubdirectory.Trim());
}
foreach (var subdirectory in subdirectories) foreach (string subdirectory in subdirectories)
{ Process.Start("CMD.exe", GetLinkCommand(subdirectory, targetDirectory));
System.Diagnostics.Process.Start("CMD.exe",GetLinkCommand(subdirectory, targetDirectory));
}
EditorUtility.RevealInFinder(targetDirectory + Path.DirectorySeparatorChar + "Assets"); 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) private static string GetLinkCommand(string subdirectory, string targetDirectory) =>
{ $"/c mklink /J \"{targetDirectory}{Path.DirectorySeparatorChar}{subdirectory}\" \"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}{subdirectory}\"";
return $"/c mklink /J \"{targetDirectory}{Path.DirectorySeparatorChar}{subdirectory}\" \"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}{subdirectory}\"";
}
} }
} }

View File

@ -9,6 +9,17 @@ namespace NegUtils.Editor
public class AssetPath public class AssetPath
{ {
private readonly string filter;
private string path;
public AssetPath(string filter)
{
this.filter = filter;
TryFindPath();
}
public string Path public string Path
{ {
get 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() private void TryFindPath()
{ {
string[] candidates = AssetDatabase.FindAssets(filter); string[] candidates = AssetDatabase.FindAssets(filter);

View File

@ -3,15 +3,10 @@ using UnityEngine;
public class GUIDToAssetPath : EditorWindow public class GUIDToAssetPath : EditorWindow
{ {
string guid = ""; private string guid = "";
string path = ""; private string path = "";
[MenuItem("Tools/GUIDToAssetPath")]
static void CreateWindow()
{
GUIDToAssetPath window = (GUIDToAssetPath)EditorWindow.GetWindowWithRect(typeof(GUIDToAssetPath), new Rect(0, 0, 400, 120));
}
void OnGUI() private void OnGUI()
{ {
GUILayout.Label("Enter guid"); GUILayout.Label("Enter guid");
guid = GUILayout.TextField(guid); guid = GUILayout.TextField(guid);
@ -29,7 +24,14 @@ public class GUIDToAssetPath : EditorWindow
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
GUILayout.Label(path); 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("-", ""); guid = guid.Replace("-", "");

View File

@ -1,6 +1,6 @@
using System.IO; using System.IO;
using UnityEngine;
using UnityEditor; using UnityEditor;
using UnityEngine;
namespace NEG.Utils.Editor namespace NEG.Utils.Editor
{ {

View File

@ -3,7 +3,9 @@ using UnityEngine;
namespace NegUtils.Editor namespace NegUtils.Editor
{ {
public class ReadOnlyAttribute : PropertyAttribute { } public class ReadOnlyAttribute : PropertyAttribute
{
}
[CustomPropertyDrawer(typeof(ReadOnlyAttribute))] [CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
public class ReadOnlyPropertyDrawer : PropertyDrawer public class ReadOnlyPropertyDrawer : PropertyDrawer
@ -15,9 +17,7 @@ namespace NegUtils.Editor
GUI.enabled = true; GUI.enabled = true;
} }
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) public override float GetPropertyHeight(SerializedProperty property, GUIContent label) =>
{ EditorGUI.GetPropertyHeight(property, label, true);
return EditorGUI.GetPropertyHeight(property, label, true);
}
} }
} }

View File

@ -1,5 +1,6 @@
using UnityEngine;
using UnityEditor; using UnityEditor;
using UnityEngine;
/// <summary> /// <summary>
/// Drawer for the RequireInterface attribute. /// Drawer for the RequireInterface attribute.
/// </summary> /// </summary>
@ -21,11 +22,12 @@ namespace NEG.Utils
if (property.propertyType == SerializedPropertyType.ObjectReference) if (property.propertyType == SerializedPropertyType.ObjectReference)
{ {
// Get attribute parameters. // Get attribute parameters.
var requiredAttribute = this.attribute as RequireInterfaceAttribute; var requiredAttribute = attribute as RequireInterfaceAttribute;
// Begin drawing property field. // Begin drawing property field.
EditorGUI.BeginProperty(position, label, property); EditorGUI.BeginProperty(position, label, property);
// Draw property field. // 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. // Finish drawing property field.
EditorGUI.EndProperty(); EditorGUI.EndProperty();
} }

View File

@ -1,5 +1,4 @@
using System.IO; using UnityEditor;
using UnityEditor;
using UnityEngine; using UnityEngine;
namespace NEG.Editor namespace NEG.Editor
@ -14,8 +13,6 @@ namespace NEG.Editor
return; return;
ScreenCapture.CaptureScreenshot(path); ScreenCapture.CaptureScreenshot(path);
}
}
} }
} }

View File

@ -1,19 +1,14 @@
using System;
using UnityEditor; using UnityEditor;
namespace NEG.Utils.Serialization namespace NEG.Utils.Serialization
{ {
public static class SerializationExtentions public static class SerializationExtentions
{ {
public static SerializedProperty FindAutoProperty(this SerializedObject @this, string name) public static SerializedProperty FindAutoProperty(this SerializedObject @this, string name) =>
{ @this.FindProperty(GetBackingFieldName(name));
return @this.FindProperty(GetBackingFieldName(name));
}
public static SerializedProperty FindAutoPropertyRelative(this SerializedProperty @this, string name) public static SerializedProperty FindAutoPropertyRelative(this SerializedProperty @this, string name) =>
{ @this.FindPropertyRelative(GetBackingFieldName(name));
return @this.FindPropertyRelative(GetBackingFieldName(name));
}
public static string GetBackingFieldName(string name) public static string GetBackingFieldName(string name)
{ {

View File

@ -1,5 +1,4 @@
using System; using System.IO;
using System.IO;
using UnityEditor; using UnityEditor;
using UnityEditor.SceneManagement; using UnityEditor.SceneManagement;
using UnityEngine; using UnityEngine;
@ -17,13 +16,6 @@ namespace NegUtils.Editor
EditorApplication.playModeStateChanged += OnPlayModeStateChanged; EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
} }
[MenuItem("Tools/Show Tools Window")]
private static void ShowWindow()
{
var window = GetWindow<ToolsWindowBase>();
window.Show();
}
protected virtual void OnGUI() protected virtual void OnGUI()
{ {
if (GUILayout.Button("Select Scene")) if (GUILayout.Button("Select Scene"))
@ -31,27 +23,25 @@ namespace NegUtils.Editor
bool startFromSceneIndex0 = EditorPrefs.GetBool("StartFromSceneIndex0"); bool startFromSceneIndex0 = EditorPrefs.GetBool("StartFromSceneIndex0");
bool newVal = GUILayout.Toggle(startFromSceneIndex0, "Start from scene with index 0 on start"); bool newVal = GUILayout.Toggle(startFromSceneIndex0, "Start from scene with index 0 on start");
if (newVal != startFromSceneIndex0) if (newVal != startFromSceneIndex0) EditorPrefs.SetBool("StartFromSceneIndex0", newVal);
{
EditorPrefs.SetBool("StartFromSceneIndex0", newVal);
}
if (!startFromSceneIndex0) if (!startFromSceneIndex0)
return; return;
bool goToCurrentScene = EditorPrefs.GetBool("GoToCurrentSceneAfterPlay"); bool goToCurrentScene = EditorPrefs.GetBool("GoToCurrentSceneAfterPlay");
newVal = GUILayout.Toggle(goToCurrentScene, "Go to current scene after play"); newVal = GUILayout.Toggle(goToCurrentScene, "Go to current scene after play");
if (newVal != goToCurrentScene) if (newVal != goToCurrentScene) EditorPrefs.SetBool("GoToCurrentSceneAfterPlay", newVal);
{
EditorPrefs.SetBool("GoToCurrentSceneAfterPlay", newVal);
}
bool goToFirstScene = EditorPrefs.GetBool("GoToFirstSceneAfterPlay"); bool goToFirstScene = EditorPrefs.GetBool("GoToFirstSceneAfterPlay");
newVal = GUILayout.Toggle(goToFirstScene, "Go to scene with index 1 after play"); newVal = GUILayout.Toggle(goToFirstScene, "Go to scene with index 1 after play");
if (newVal != goToFirstScene) if (newVal != goToFirstScene) EditorPrefs.SetBool("GoToFirstSceneAfterPlay", newVal);
{
EditorPrefs.SetBool("GoToFirstSceneAfterPlay", newVal);
} }
[MenuItem("Tools/Show Tools Window")]
private static void ShowWindow()
{
var window = GetWindow<ToolsWindowBase>();
window.Show();
} }
private static void ShowScenesList(Rect position) private static void ShowScenesList(Rect position)
@ -71,7 +61,11 @@ namespace NegUtils.Editor
for (int i = 0; i < fileInfo.Length; i++) for (int i = 0; i < fileInfo.Length; i++)
{ {
string s = fileInfo[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, () => { menu.AddItem(
new GUIContent(s.Remove(0, basePath.Length + 1)
.Remove(s.Length - basePath.Length - UnitySceneExtensionLength - 1, UnitySceneExtensionLength)
.Replace('\\', '/')), false, () =>
{
LoadScene(s); LoadScene(s);
}); });
@ -80,10 +74,7 @@ namespace NegUtils.Editor
} }
string[] dirInfo = Directory.GetDirectories(path); string[] dirInfo = Directory.GetDirectories(path);
foreach (string dir in dirInfo) foreach (string dir in dirInfo) AddFiles(dir, basePath, menu);
{
AddFiles(dir, basePath, menu);
}
} }
private static void LoadScene(string path) private static void LoadScene(string path)
@ -125,7 +116,6 @@ namespace NegUtils.Editor
} }
break; break;
} }
} }
} }
} }

View File

@ -1,7 +1,5 @@
using System.IO; using System.IO;
using UnityEditor;
using UnityEditor.AssetImporters; using UnityEditor.AssetImporters;
using UnityEditor.Experimental.AssetImporters;
using UnityEngine; using UnityEngine;
[ScriptedImporter(1, "tsv")] [ScriptedImporter(1, "tsv")]

View File

@ -7,8 +7,7 @@ namespace NEG.Utils
{ {
public class KeyBasedFactory<T1, T2> public class KeyBasedFactory<T1, T2>
{ {
[PublicAPI] [PublicAPI] protected Dictionary<T1, Type> data;
protected Dictionary<T1, Type> data;
public KeyBasedFactory() public KeyBasedFactory()
{ {
@ -32,14 +31,10 @@ namespace NEG.Utils
var methodFields = var methodFields =
type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
for (int i = 0; i < methodFields.Length; i++) for (int i = 0; i < methodFields.Length; i++)
{
if (Attribute.GetCustomAttribute(methodFields[i], typeof(FactoryRegistration)) != null) if (Attribute.GetCustomAttribute(methodFields[i], typeof(FactoryRegistration)) != null)
{
methodFields[i].Invoke(null, Array.Empty<object>()); methodFields[i].Invoke(null, Array.Empty<object>());
} }
} }
}
}
public void Register(T1 key, Type type) => data.Add(key, type); public void Register(T1 key, Type type) => data.Add(key, type);
@ -49,6 +44,5 @@ namespace NEG.Utils
[AttributeUsage(AttributeTargets.Method)] [AttributeUsage(AttributeTargets.Method)]
public class FactoryRegistration : Attribute public class FactoryRegistration : Attribute
{ {
public FactoryRegistration() { }
} }
} }

View File

@ -4,15 +4,15 @@ namespace NegUtils.NEG.UI
{ {
public interface IControllable public interface IControllable
{ {
public class BackUsed
{
public bool Used { get; set; }
}
event Action<object> OnOpened; event Action<object> OnOpened;
event Action OnClosed; event Action OnClosed;
event Action<BackUsed> OnBackUsed; event Action<BackUsed> OnBackUsed;
public void TryUseBack(ref BackUsed backUsed); public void TryUseBack(ref BackUsed backUsed);
public class BackUsed
{
public bool Used { get; set; }
}
} }
} }

View File

@ -1,7 +1,9 @@
{ {
"name": "NEG.UI", "name": "NEG.UI",
"rootNamespace": "", "rootNamespace": "",
"references": ["GUID:3c4294719a93e3c4e831a9ff0c261e8a"], "references": [
"GUID:3c4294719a93e3c4e831a9ff0c261e8a"
],
"includePlatforms": [], "includePlatforms": [],
"excludePlatforms": [], "excludePlatforms": [],
"allowUnsafeCode": false, "allowUnsafeCode": false,

View File

@ -5,13 +5,14 @@ namespace NEG.UI.Popup
{ {
public class DefaultPopupData : PopupData public class DefaultPopupData : PopupData
{ {
private readonly IDefaultPopup defaultPopup;
private readonly string title;
private readonly string content; private readonly string content;
private readonly IDefaultPopup defaultPopup;
private readonly List<(string, Action)> options; 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; defaultPopup = popup;
this.title = title; this.title = title;

View File

@ -10,7 +10,10 @@ namespace NEG.UI.Popup
/// </summary> /// </summary>
/// <param name="title">popup title</param> /// <param name="title">popup title</param>
/// <param name="content">popup content</param> /// <param name="content">popup content</param>
/// <param name="options">list of tuples (name, action on click), to set buttons. Do not pass here popup closing logic, implementing class should do it</param> /// <param name="options">
/// list of tuples (name, action on click), to set buttons. Do not pass here popup closing logic,
/// implementing class should do it
/// </param>
public void SetContent(string title, string content, List<(string name, Action action)> options); public void SetContent(string title, string content, List<(string name, Action action)> options);
} }
} }

View File

@ -6,20 +6,6 @@ namespace NEG.UI.Popup
[PublicAPI] [PublicAPI]
public class PopupData public class PopupData
{ {
/// <summary>
/// Event that is fired on closing popup.
/// </summary>
public event Action<PopupData> PopupClosedEvent
{
add => popup.OnPopupClosed += value;
remove => popup.OnPopupClosed -= value;
}
/// <summary>
/// Is this data is still valid. If set to false, popup will not show.
/// </summary>
public bool IsValid { get; protected set; }
private readonly IPopup popup; private readonly IPopup popup;
/// <summary> /// <summary>
@ -32,6 +18,20 @@ namespace NEG.UI.Popup
IsValid = true; IsValid = true;
} }
/// <summary>
/// Is this data is still valid. If set to false, popup will not show.
/// </summary>
public bool IsValid { get; protected set; }
/// <summary>
/// Event that is fired on closing popup.
/// </summary>
public event Action<PopupData> PopupClosedEvent
{
add => popup.OnPopupClosed += value;
remove => popup.OnPopupClosed -= value;
}
/// <summary> /// <summary>
/// Show popup and pass needed data. /// Show popup and pass needed data.
/// </summary> /// </summary>

View File

@ -489,7 +489,7 @@ namespace System.Collections.Generic
{ {
int i = 0; int i = 0;
(TElement, TPriority)[] nodes = _nodes; (TElement, TPriority)[] nodes = _nodes;
foreach ((var element, var priority) in items) foreach (var (element, priority) in items)
{ {
if (nodes.Length == i) if (nodes.Length == i)
{ {
@ -509,7 +509,7 @@ namespace System.Collections.Generic
} }
else else
{ {
foreach ((var element, var priority) in items) Enqueue(element, priority); foreach (var (element, priority) in items) Enqueue(element, priority);
} }
} }

View File

@ -2,7 +2,6 @@ using JetBrains.Annotations;
using NEG.UI.Area; using NEG.UI.Area;
using NEG.UI.Popup; using NEG.UI.Popup;
using NEG.UI.Window; using NEG.UI.Window;
using NEG.Utils;
using NegUtils.NEG.UI; using NegUtils.NEG.UI;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -14,6 +13,31 @@ namespace NEG.UI
[PublicAPI] [PublicAPI]
public abstract class UiManager : IDisposable public abstract class UiManager : IDisposable
{ {
private IArea currentArea;
protected IDefaultPopup currentDefaultPopup;
private (PopupData data, int priority) currentShownPopup;
//TODO: localize
private string localizedYes = "Yes", localizedNo = "No", localizedOk = "Ok";
private List<IWindow> mainWindows;
private PriorityQueue<PopupData, int> popupsToShow = new();
protected UiManager(IArea startArea)
{
if (Instance != null)
{
Debug.LogError("Only one instance od UiManager is allowed");
return;
}
Instance = this;
CurrentArea = startArea;
mainWindows = new List<IWindow>();
}
public static UiManager Instance { get; protected set; } public static UiManager Instance { get; protected set; }
/// <summary> /// <summary>
@ -39,33 +63,11 @@ namespace NEG.UI
public PopupData CurrentPopup => currentShownPopup.data; public PopupData CurrentPopup => currentShownPopup.data;
private IArea currentArea; public virtual void Dispose() => Instance = null;
private (PopupData data, int priority) currentShownPopup;
protected IDefaultPopup currentDefaultPopup;
private PriorityQueue<PopupData, int> popupsToShow = new();
//TODO: localize
private string localizedYes = "Yes", localizedNo = "No", localizedOk = "Ok";
private List<IWindow> mainWindows;
protected UiManager(IArea startArea)
{
if (Instance != null)
{
Debug.LogError("Only one instance od UiManager is allowed");
return;
}
Instance = this;
CurrentArea = startArea;
mainWindows = new List<IWindow>();
}
/// <summary> /// <summary>
/// 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. /// 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.
/// </summary> /// </summary>
/// <param name="title">popup title</param> /// <param name="title">popup title</param>
/// <param name="content">popup content</param> /// <param name="content">popup content</param>
@ -74,16 +76,18 @@ namespace NEG.UI
/// <param name="priority">priority of popup (lower number -> show first)</param> /// <param name="priority">priority of popup (lower number -> show first)</param>
/// <param name="forceShow">force show current popup only if currently shown has lower priority</param> /// <param name="forceShow">force show current popup only if currently shown has lower priority</param>
/// <returns>data for created popup, can be used to invalidate popup (will not show)</returns> /// <returns>data for created popup, can be used to invalidate popup (will not show)</returns>
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, 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); ShowPopup(data, priority, forceShow);
return data; return data;
} }
/// <summary> /// <summary>
/// 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.
/// </summary> /// </summary>
/// <param name="title">popup title</param> /// <param name="title">popup title</param>
/// <param name="content">popup content</param> /// <param name="content">popup content</param>
@ -94,16 +98,21 @@ namespace NEG.UI
/// <param name="priority">priority of popup (lower number -> show first)</param> /// <param name="priority">priority of popup (lower number -> show first)</param>
/// <param name="forceShow">force show current popup only if currently shown has lower priority</param> /// <param name="forceShow">force show current popup only if currently shown has lower priority</param>
/// <returns>data for created popup, can be used to invalidate popup (will not show)</returns> /// <returns>data for created popup, can be used to invalidate popup (will not show)</returns>
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, 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); ShowPopup(data, priority, forceShow);
return data; return data;
} }
/// <summary> /// <summary>
/// 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.
/// </summary> /// </summary>
/// <param name="title">popup title</param> /// <param name="title">popup title</param>
/// <param name="content">popup content</param> /// <param name="content">popup content</param>
@ -111,7 +120,8 @@ namespace NEG.UI
/// <param name="priority">priority of popup (lower number -> show first)</param> /// <param name="priority">priority of popup (lower number -> show first)</param>
/// <param name="forceShow">force show current popup only if currently shown has lower priority</param> /// <param name="forceShow">force show current popup only if currently shown has lower priority</param>
/// <returns>data for created popup, can be used to invalidate popup (will not show)</returns> /// <returns>data for created popup, can be used to invalidate popup (will not show)</returns>
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); var data = new DefaultPopupData(currentDefaultPopup, title, content, actions);
ShowPopup(data, priority, forceShow); ShowPopup(data, priority, forceShow);
@ -148,8 +158,6 @@ namespace NEG.UI
UpdatePopupsState(false); 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); public void MainWindowClosed(IWindow window) => mainWindows.Remove(window);
@ -160,10 +168,8 @@ namespace NEG.UI
protected void PopupClosed(PopupData data) protected void PopupClosed(PopupData data)
{ {
if (currentShownPopup.data != data) if (currentShownPopup.data != data)
{
//Debug.LogError("Popup was not shown"); //Debug.LogError("Popup was not shown");
return; return;
}
UpdatePopupsState(false); UpdatePopupsState(false);
} }
@ -208,11 +214,10 @@ namespace NEG.UI
currentShownPopup.data.PopupClosedEvent -= PopupClosed; currentShownPopup.data.PopupClosedEvent -= PopupClosed;
currentShownPopup.data.Hide(); currentShownPopup.data.Hide();
} }
currentShownPopup = (data, priority); currentShownPopup = (data, priority);
data.Show(); data.Show();
data.PopupClosedEvent += PopupClosed; data.PopupClosedEvent += PopupClosed;
} }
} }
} }

View File

@ -1,12 +1,10 @@
using NEG.UI.UnityUi.Window; using NEG.UI.UnityUi.Window;
using NEG.UI.Window; using NEG.UI.Window;
using System;
using KBCore.Refs;
using UnityEngine; using UnityEngine;
namespace NEG.UI.Area namespace NEG.UI.Area
{ {
[Tooltip(tooltip: "Automatically open attached window on start")] [Tooltip("Automatically open attached window on start")]
public class AutoWindowOpen : MonoBehaviour public class AutoWindowOpen : MonoBehaviour
{ {
[SerializeField] private MonoWindow window; [SerializeField] private MonoWindow window;

View File

@ -1,9 +1,6 @@
using KBCore.Refs; using NEG.UI.UnityUi;
using NEG.UI.UnityUi;
using NEG.UI.Window; using NEG.UI.Window;
using NegUtils.NEG.UI; using NegUtils.NEG.UI;
using System;
using UnityEngine;
namespace NEG.UI.Area namespace NEG.UI.Area
{ {

View File

@ -1,40 +1,19 @@
using System.Collections.Generic; using NEG.UI.UnityUi.WindowSlot;
using UnityEngine;
using NEG.UI.Popup;
using NEG.UI.UnityUi.Window;
using NEG.UI.UnityUi.WindowSlot;
using NEG.UI.Window; using NEG.UI.Window;
using NEG.UI.WindowSlot; using NEG.UI.WindowSlot;
using NegUtils.NEG.UI; using NegUtils.NEG.UI;
using System; using System;
using System.Collections.Generic;
using UnityEngine;
namespace NEG.UI.Area namespace NEG.UI.Area
{ {
public class MonoArea : MonoBehaviour, IArea public class MonoArea : MonoBehaviour, IArea
{ {
public event Action<object> OnOpened;
public event Action OnClosed;
public event Action<IControllable.BackUsed> OnBackUsed;
public IEnumerable<IWindowSlot> AvailableSlots => windowSlots;
public IWindowSlot DefaultWindowSlot => windowSlots[0];
[SerializeField] private bool setAsDefaultArea; [SerializeField] private bool setAsDefaultArea;
[SerializeField] private List<MonoWindowSlot> windowSlots; [SerializeField] private List<MonoWindowSlot> windowSlots;
public IWindowSlot DefaultWindowSlot => windowSlots[0];
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);
protected virtual void Awake() protected virtual void Awake()
{ {
@ -54,6 +33,26 @@ namespace NEG.UI.Area
UiManager.Instance.CurrentArea = null; UiManager.Instance.CurrentArea = null;
} }
public event Action<object> OnOpened;
public event Action OnClosed;
public event Action<IControllable.BackUsed> OnBackUsed;
public IEnumerable<IWindowSlot> 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); public void TryUseBack(ref IControllable.BackUsed backUsed) => OnBackUsed?.Invoke(backUsed);
} }
} }

View File

@ -6,7 +6,6 @@ using System.Collections.Generic;
using TMPro; using TMPro;
using UnityEngine; using UnityEngine;
using UnityEngine.EventSystems; using UnityEngine.EventSystems;
using UnityEngine.Serialization;
using UnityEngine.UI; using UnityEngine.UI;
namespace NEG.UI.UnityUi.Buttons namespace NEG.UI.UnityUi.Buttons
@ -16,26 +15,35 @@ namespace NEG.UI.UnityUi.Buttons
public class BaseButton : MonoBehaviour, ISelectHandler, IDeselectHandler, IPointerEnterHandler, IPointerExitHandler public class BaseButton : MonoBehaviour, ISelectHandler, IDeselectHandler, IPointerEnterHandler, IPointerExitHandler
{ {
public delegate void SelectionHandler(bool isSilent); public delegate void SelectionHandler(bool isSilent);
/// <summary>
/// is silent [SerializeField] [Self(Flag.Optional)] private Button button;
/// </summary>
public event SelectionHandler OnSelected; [SerializeField] [Child(Flag.Optional)]
public event SelectionHandler OnDeselected; private TMP_Text text;
public event Action OnButtonPressed;
[SerializeField] [Child(Flag.Optional)]
private Image icon;
[SerializeField] private ButtonSettings groupButtonSettings;
private readonly Dictionary<string, ButtonElementBehaviour> behaviours = new();
public bool Interactable { get => button.interactable; set => button.interactable = value; } public bool Interactable { get => button.interactable; set => button.interactable = value; }
public TMP_Text Text => text; public TMP_Text Text => text;
[SerializeField, Self(Flag.Optional)] private Button button; protected virtual void Awake()
[SerializeField, Child(Flag.Optional)] private TMP_Text text; {
[SerializeField, Child(Flag.Optional)] private Image icon; button.onClick.AddListener(OnClicked);
if (groupButtonSettings == null)
MonoUiManager.Instance.DefaultUiSettings.Apply(this);
else
groupButtonSettings.Apply(this);
}
[SerializeField] private ButtonSettings groupButtonSettings; private void Start() => OnDeselect(null);
private readonly Dictionary<string, ButtonElementBehaviour> behaviours = new Dictionary<string, ButtonElementBehaviour>(); private void OnValidate() => this.ValidateRefs();
public virtual void OnSelect(BaseEventData eventData) => OnSelected?.Invoke(eventData is SilentEventData);
public void OnDeselect(BaseEventData eventData) => OnDeselected?.Invoke(eventData is SilentEventData); public void OnDeselect(BaseEventData eventData) => OnDeselected?.Invoke(eventData is SilentEventData);
@ -47,6 +55,16 @@ namespace NEG.UI.UnityUi.Buttons
EventSystem.current.SetSelectedGameObject(null); EventSystem.current.SetSelectedGameObject(null);
} }
public virtual void OnSelect(BaseEventData eventData) => OnSelected?.Invoke(eventData is SilentEventData);
/// <summary>
/// is silent
/// </summary>
public event SelectionHandler OnSelected;
public event SelectionHandler OnDeselected;
public event Action OnButtonPressed;
public void SetText(string txt) public void SetText(string txt)
{ {
if (text == null) if (text == null)
@ -61,6 +79,7 @@ namespace NEG.UI.UnityUi.Buttons
setting.ChangeData(data); setting.ChangeData(data);
return; return;
} }
behaviours.Add(data.Key, MonoUiManager.Instance.BehavioursFactory.CreateInstance(data.Key, this, data)); behaviours.Add(data.Key, MonoUiManager.Instance.BehavioursFactory.CreateInstance(data.Key, this, data));
} }
@ -71,23 +90,11 @@ namespace NEG.UI.UnityUi.Buttons
Debug.LogError($"Behaviour with key {key} was not found"); Debug.LogError($"Behaviour with key {key} was not found");
return; return;
} }
setting.Dispose(); setting.Dispose();
behaviours.Remove(key); behaviours.Remove(key);
} }
protected virtual void Awake()
{
button.onClick.AddListener(OnClicked);
if (groupButtonSettings == null)
MonoUiManager.Instance.DefaultUiSettings.Apply(this);
else
groupButtonSettings.Apply(this);
}
private void Start() => OnDeselect(null);
private void OnValidate() => this.ValidateRefs();
protected virtual void OnClicked() protected virtual void OnClicked()
{ {
OnDeselect(null); OnDeselect(null);

View File

@ -1,5 +1,4 @@
using System; using KBCore.Refs;
using KBCore.Refs;
using UnityEngine; using UnityEngine;
namespace NEG.UI.UnityUi.Buttons namespace NEG.UI.UnityUi.Buttons
@ -7,7 +6,7 @@ namespace NEG.UI.UnityUi.Buttons
[RequireComponent(typeof(BaseButton))] [RequireComponent(typeof(BaseButton))]
public abstract class ButtonReaction : MonoBehaviour 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 Awake() => button.OnButtonPressed += OnClicked;

View File

@ -1,6 +1,3 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine; using UnityEngine;
using UnityEngine.SceneManagement; using UnityEngine.SceneManagement;
@ -9,8 +6,8 @@ namespace NEG.UI.UnityUi.Buttons
[RequireComponent(typeof(BaseButton))] [RequireComponent(typeof(BaseButton))]
public class ChangeSceneButton : ButtonReaction public class ChangeSceneButton : ButtonReaction
{ {
[Header("Leave empty to use int value")] [Header("Leave empty to use int value")] [SerializeField]
[SerializeField] private string sceneName; private string sceneName;
[SerializeField] private int sceneIndex; [SerializeField] private int sceneIndex;

View File

@ -1,6 +1,4 @@
using UnityEngine; namespace NEG.UI.UnityUi.Buttons
namespace NEG.UI.UnityUi.Buttons
{ {
public class CloseAllWindows : ButtonReaction public class CloseAllWindows : ButtonReaction
{ {

View File

@ -1,6 +1,5 @@
using NEG.UI.UnityUi.Window; using NEG.UI.UnityUi.Window;
using NEG.UI.Window; using NEG.UI.Window;
using System;
using UnityEngine; using UnityEngine;
namespace NEG.UI.UnityUi.Buttons namespace NEG.UI.UnityUi.Buttons
@ -10,13 +9,13 @@ namespace NEG.UI.UnityUi.Buttons
{ {
[SerializeField] private MonoWindow windowToClose; [SerializeField] private MonoWindow windowToClose;
protected override void OnClicked() => windowToClose.Close();
private void OnValidate() private void OnValidate()
{ {
if (windowToClose != null) if (windowToClose != null)
return; return;
windowToClose = GetComponentInParent<MonoWindow>(); windowToClose = GetComponentInParent<MonoWindow>();
} }
protected override void OnClicked() => windowToClose.Close();
} }
} }

View File

@ -38,6 +38,7 @@ namespace NEG.UI.UnityUi.Buttons
default: default:
throw new ArgumentOutOfRangeException(); throw new ArgumentOutOfRangeException();
} }
base.OnMove(eventData); base.OnMove(eventData);
} }

View File

@ -1,5 +1,4 @@
using KBCore.Refs; using NEG.UI.UnityUi.Window;
using NEG.UI.UnityUi.Window;
using NEG.UI.Window; using NEG.UI.Window;
using UnityEngine; using UnityEngine;
@ -7,8 +6,7 @@ namespace NEG.UI.UnityUi.Buttons
{ {
public class OpenAsCurrentMainChild : ButtonReaction public class OpenAsCurrentMainChild : ButtonReaction
{ {
[SerializeField] [SerializeField] private MonoWindow windowToOpen;
private MonoWindow windowToOpen;
protected override void OnClicked() => UiManager.Instance.CurrentMainWindow.OpenAsChild(windowToOpen); protected override void OnClicked() => UiManager.Instance.CurrentMainWindow.OpenAsChild(windowToOpen);
} }

View File

@ -1,9 +1,7 @@
using NEG.UI.UnityUi.Window; using NEG.UI.UnityUi.Window;
using NEG.UI.UnityUi.WindowSlot; using NEG.UI.UnityUi.WindowSlot;
using System;
using UnityEngine;
using NEG.UI.Window; using NEG.UI.Window;
using NEG.UI.WindowSlot; using UnityEngine;
namespace NEG.UI.UnityUi.Buttons namespace NEG.UI.UnityUi.Buttons
{ {
@ -11,8 +9,9 @@ namespace NEG.UI.UnityUi.Buttons
public class OpenWindow : ButtonReaction public class OpenWindow : ButtonReaction
{ {
[SerializeField] private MonoWindow window; [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); protected override void OnClicked() => window.Open(slot);
} }

View File

@ -1,13 +1,12 @@
using NEG.UI.UnityUi.Buttons.Settings; using NEG.UI.UnityUi.Buttons.Settings;
using System; using System;
using UnityEngine.EventSystems;
namespace NEG.UI.UnityUi.Buttons.Reaction namespace NEG.UI.UnityUi.Buttons.Reaction
{ {
public abstract class ButtonElementBehaviour : IDisposable public abstract class ButtonElementBehaviour : IDisposable
{ {
protected SettingData baseData;
protected readonly BaseButton button; protected readonly BaseButton button;
protected SettingData baseData;
public ButtonElementBehaviour(BaseButton baseButton, SettingData settingData) public ButtonElementBehaviour(BaseButton baseButton, SettingData settingData)
{ {
@ -15,8 +14,8 @@ namespace NEG.UI.UnityUi.Buttons.Reaction
baseData = settingData; baseData = settingData;
} }
public virtual void ChangeData(SettingData newData) => baseData = newData;
public abstract void Dispose(); public abstract void Dispose();
public virtual void ChangeData(SettingData newData) => baseData = newData;
} }
} }

View File

@ -1,7 +1,6 @@
using NEG.UI.UnityUi.Buttons.Settings; using NEG.UI.UnityUi.Buttons.Settings;
using NEG.Utils; using NEG.Utils;
using UnityEngine; using UnityEngine;
using UnityEngine.EventSystems;
namespace NEG.UI.UnityUi.Buttons.Reaction namespace NEG.UI.UnityUi.Buttons.Reaction
{ {
@ -38,6 +37,5 @@ namespace NEG.UI.UnityUi.Buttons.Reaction
private void OnButtonSelected(bool _) => button.Text.color = data.SelectedColor; private void OnButtonSelected(bool _) => button.Text.color = data.SelectedColor;
private void OnButtonDeselected(bool _) => button.Text.color = data.DeselectedColor; private void OnButtonDeselected(bool _) => button.Text.color = data.DeselectedColor;
} }
} }

View File

@ -1,7 +1,4 @@
using NEG.UI.UnityUi.Buttons.Settings; #if FMOD
using NEG.Utils;
#if FMOD
namespace NEG.UI.UnityUi.Buttons.Reaction namespace NEG.UI.UnityUi.Buttons.Reaction
{ {
public class SimpleSoundBehaviour : ButtonElementBehaviour public class SimpleSoundBehaviour : ButtonElementBehaviour

View File

@ -1,8 +1,5 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine; using UnityEngine;
using UnityEngine.UI;
namespace NEG.UI.UnityUi.Buttons.Settings namespace NEG.UI.UnityUi.Buttons.Settings
{ {
@ -12,10 +9,7 @@ namespace NEG.UI.UnityUi.Buttons.Settings
public void Apply(BaseButton button) public void Apply(BaseButton button)
{ {
foreach (var setting in settingDatas) foreach (var setting in settingDatas) setting.Apply(button);
{
setting.Apply(button);
}
} }
[ContextMenu("Refresh")] [ContextMenu("Refresh")]
@ -23,10 +17,7 @@ namespace NEG.UI.UnityUi.Buttons.Settings
{ {
settingDatas.Clear(); settingDatas.Clear();
var components = GetComponents<SettingData>(); var components = GetComponents<SettingData>();
foreach (var data in components) foreach (var data in components) settingDatas.Add(data);
{
settingDatas.Add(data);
}
} }
} }
} }

View File

@ -1,16 +1,12 @@
using KBCore.Refs; using KBCore.Refs;
using System;
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization;
namespace NEG.UI.UnityUi.Buttons.Settings namespace NEG.UI.UnityUi.Buttons.Settings
{ {
public abstract class SettingData : MonoBehaviour public abstract class SettingData : MonoBehaviour
{ {
[field: SerializeField] public string Key { get; private set; } [field: SerializeField] public string Key { get; private set; }
[SerializeField, Self(Flag.Optional)] private BaseButton attachedButton; [SerializeField] [Self(Flag.Optional)] private BaseButton attachedButton;
public virtual void Apply(BaseButton button) => button.AddOrOverrideSetting(this);
private void Awake() private void Awake()
{ {
@ -24,5 +20,7 @@ namespace NEG.UI.UnityUi.Buttons.Settings
if (attachedButton == null && TryGetComponent(out ButtonSettings settings)) if (attachedButton == null && TryGetComponent(out ButtonSettings settings))
settings.Refresh(); settings.Refresh();
} }
public virtual void Apply(BaseButton button) => button.AddOrOverrideSetting(this);
} }
} }

View File

@ -5,13 +5,17 @@ using System.Collections.Generic;
using TMPro; using TMPro;
using UnityEngine; using UnityEngine;
namespace NEG.UI.UnityUi namespace NEG.UI.UnityUi
{ {
[PublicAPI] [PublicAPI]
public class CarouselList : MonoBehaviour public class CarouselList : MonoBehaviour
{ {
public event Action<int> OnSelectedItemChanged; [SerializeField] private BaseButton nextButton;
[SerializeField] private BaseButton prevButton;
[SerializeField] private TMP_Text currentOptionText;
private List<string> options;
/// <summary> /// <summary>
/// Current option /// Current option
/// </summary> /// </summary>
@ -22,11 +26,19 @@ namespace NEG.UI.UnityUi
/// </summary> /// </summary>
public int CurrentOptionId { get; private set; } public int CurrentOptionId { get; private set; }
[SerializeField] private BaseButton nextButton; private void Awake()
[SerializeField] private BaseButton prevButton; {
[SerializeField] private TMP_Text currentOptionText; nextButton.OnButtonPressed += SelectNextOption;
prevButton.OnButtonPressed += SelectPrevOption;
}
private List<string> options; private void OnDestroy()
{
nextButton.OnButtonPressed -= SelectNextOption;
prevButton.OnButtonPressed -= SelectPrevOption;
}
public event Action<int> OnSelectedItemChanged;
/// <summary> /// <summary>
/// Sets new options list, automatically first will be selected. /// Sets new options list, automatically first will be selected.
@ -52,6 +64,7 @@ namespace NEG.UI.UnityUi
Debug.LogError("Invalid option number"); Debug.LogError("Invalid option number");
return; return;
} }
CurrentOptionId = option; CurrentOptionId = option;
CurrentOption = options[option]; CurrentOption = options[option];
currentOptionText.text = CurrentOption; currentOptionText.text = CurrentOption;
@ -80,18 +93,7 @@ namespace NEG.UI.UnityUi
SelectOption(index); SelectOption(index);
} }
private void Awake() private void ChangeOption(bool next) =>
{ SelectOption((CurrentOptionId + (next ? 1 : -1) + options.Count) % options.Count);
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);
} }
} }

View File

@ -1,6 +1,4 @@
using NEG.UI.UnityUi.Buttons; using NEG.UI.UnityUi.Buttons;
using System.Collections.Generic;
using System.IO;
using UnityEditor; using UnityEditor;
using UnityEngine; using UnityEngine;
using UnityEngine.UI; using UnityEngine.UI;
@ -37,6 +35,5 @@ namespace NEG.UI.UnityUi.Editor
scriptProperty.objectReferenceValue = chosenTextAsset; scriptProperty.objectReferenceValue = chosenTextAsset;
so.ApplyModifiedProperties(); so.ApplyModifiedProperties();
} }
} }
} }

View File

@ -1,16 +1,16 @@
using UnityEditor; using NEG.UI.UnityUi.Buttons;
using UnityEditor;
using UnityEditor.UI; using UnityEditor.UI;
using UnityEngine.UIElements;
namespace NEG.UI.UnityUi.Editor namespace NEG.UI.UnityUi.Editor
{ {
[CustomEditor(typeof(Buttons.CustomNavigationButton), true)] [CustomEditor(typeof(CustomNavigationButton), true)]
public class CustomNavigationButtonEditor : ButtonEditor public class CustomNavigationButtonEditor : ButtonEditor
{ {
private SerializedProperty upOverrideProperty;
private SerializedProperty downOverrideProperty; private SerializedProperty downOverrideProperty;
private SerializedProperty leftOverrideProperty; private SerializedProperty leftOverrideProperty;
private SerializedProperty rightOverrideProperty; private SerializedProperty rightOverrideProperty;
private SerializedProperty upOverrideProperty;
protected override void OnEnable() protected override void OnEnable()
{ {

View File

@ -6,7 +6,6 @@ using UnityEngine;
using UnityEngine.UI; using UnityEngine.UI;
using UnityEngine.UIElements; using UnityEngine.UIElements;
using ObjectField = UnityEditor.Search.ObjectField; using ObjectField = UnityEditor.Search.ObjectField;
using Toggle = UnityEngine.UIElements.Toggle; using Toggle = UnityEngine.UIElements.Toggle;
namespace NEG.UI.UnityUi.Editor namespace NEG.UI.UnityUi.Editor
@ -30,8 +29,10 @@ namespace NEG.UI.UnityUi.Editor
var unitRect = new Rect(position.x + 35, position.y, 200, position.height); 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 // 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(amountRect,
EditorGUI.PropertyField(unitRect, property.FindAutoPropertyRelative(nameof(OverridableNavigation.Selectable)), GUIContent.none); property.FindAutoPropertyRelative(nameof(OverridableNavigation.Override)), GUIContent.none);
EditorGUI.PropertyField(unitRect,
property.FindAutoPropertyRelative(nameof(OverridableNavigation.Selectable)), GUIContent.none);
// Set indent back to what it was // Set indent back to what it was
EditorGUI.indentLevel = indent; EditorGUI.indentLevel = indent;
@ -41,7 +42,7 @@ namespace NEG.UI.UnityUi.Editor
public override VisualElement CreatePropertyGUI(SerializedProperty property) public override VisualElement CreatePropertyGUI(SerializedProperty property)
{ {
var container = new VisualElement() var container = new VisualElement
{ {
style = style =
{ {
@ -53,12 +54,9 @@ namespace NEG.UI.UnityUi.Editor
}; };
string name = property.name; string name = property.name;
if (name.Length > 0) if (name.Length > 0) name = $"{char.ToUpper(name[0])}{name[1..]}";
{
name = $"{char.ToUpper(name[0])}{name[1..]}";
}
var innerContainer = new VisualElement() var innerContainer = new VisualElement
{ {
style = style =
{ {
@ -74,13 +72,7 @@ namespace NEG.UI.UnityUi.Editor
var enabler = new Toggle(); var enabler = new Toggle();
enabler.BindProperty(property.FindPropertyRelative("<Override>k__BackingField")); enabler.BindProperty(property.FindPropertyRelative("<Override>k__BackingField"));
var field = new ObjectField() var field = new ObjectField { style = { flexGrow = 100 } };
{
style =
{
flexGrow = 100
}
};
var selectableField = property.FindAutoPropertyRelative(nameof(OverridableNavigation.Selectable)); var selectableField = property.FindAutoPropertyRelative(nameof(OverridableNavigation.Selectable));

View File

@ -1,16 +1,13 @@
using KBCore.Refs; using KBCore.Refs;
using NEG.UI.UnityUi.Window; using NEG.UI.UnityUi.Window;
using NegUtils.NEG.UI; using NegUtils.NEG.UI;
using System;
using UnityEngine; using UnityEngine;
namespace NEG.UI.UnityUi namespace NEG.UI.UnityUi
{ {
public abstract class MonoController : MonoBehaviour, IController public abstract class MonoController : MonoBehaviour, IController
{ {
public IControllable Controllable => controllable.Value; [SerializeField] [Self] protected InterfaceRef<IControllable> controllable;
[SerializeField, Self] protected InterfaceRef<IControllable> controllable;
protected MonoWindow ControllableAsWindow => (MonoWindow)controllable.Value; protected MonoWindow ControllableAsWindow => (MonoWindow)controllable.Value;
@ -22,6 +19,7 @@ namespace NEG.UI.UnityUi
} }
private void OnValidate() => this.ValidateRefs(); private void OnValidate() => this.ValidateRefs();
public IControllable Controllable => controllable.Value;
protected virtual void OnOpened(object data) { } protected virtual void OnOpened(object data) { }

View File

@ -12,16 +12,20 @@ namespace NEG.UI.UnityUi
Direction Direction
} }
public class UiInputModule { public SelectionSource CurrentSelectionSource { get; protected set; }} public class UiInputModule
{
public SelectionSource CurrentSelectionSource { get; protected set; }
}
public class DefaultInputModule : UiInputModule public class DefaultInputModule : UiInputModule
{ {
public DefaultInputModule() public DefaultInputModule()
{ {
var defaultActions = new DefaultInputActions(); 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 += InputActionReference.Create(defaultActions.UI.Cancel).action.performed +=
(_) => UiManager.Instance.UseBack(); _ => UiManager.Instance.UseBack();
defaultActions.Enable(); defaultActions.Enable();
if (Gamepad.current != null) if (Gamepad.current != null)
@ -37,7 +41,7 @@ namespace NEG.UI.UnityUi
//gamepadAction.Enable(); //gamepadAction.Enable();
var mouseAction = new InputAction(binding: "/<Mouse>/*"); var mouseAction = new InputAction(binding: "/<Mouse>/*");
mouseAction.performed += (context) => mouseAction.performed += context =>
{ {
if (CurrentSelectionSource == SelectionSource.Pointer) if (CurrentSelectionSource == SelectionSource.Pointer)
return; return;
@ -48,35 +52,32 @@ namespace NEG.UI.UnityUi
private void OnSelectionChangeStarted() private void OnSelectionChangeStarted()
{ {
if(CurrentSelectionSource == SelectionSource.Direction && EventSystem.current.currentSelectedGameObject != null) if (CurrentSelectionSource == SelectionSource.Direction &&
EventSystem.current.currentSelectedGameObject != null)
return; return;
SetDirectionInput(); SetDirectionInput();
} }
private void SetDirectionInput() private void SetDirectionInput()
{ {
if (EventSystem.current == null || MonoUiManager.Instance == null ) if (EventSystem.current == null || MonoUiManager.Instance == null) return;
{
return;
}
CurrentSelectionSource = SelectionSource.Direction; CurrentSelectionSource = SelectionSource.Direction;
Cursor.visible = false; 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; return;
} }
var data = new PointerEventData(EventSystem.current); var data = new PointerEventData(EventSystem.current);
var currentSelected = EventSystem.current.currentSelectedGameObject; var currentSelected = EventSystem.current.currentSelectedGameObject;
if (currentSelected != null) if (currentSelected != null)
{
for (var current = EventSystem.current.currentSelectedGameObject.transform; for (var current = EventSystem.current.currentSelectedGameObject.transform;
current != null; current != null;
current = current.parent) current = current.parent)
{
ExecuteEvents.Execute(current.gameObject, data, ExecuteEvents.pointerExitHandler); ExecuteEvents.Execute(current.gameObject, data, ExecuteEvents.pointerExitHandler);
}
}
EventSystem.current.SetSelectedGameObject(currentSelected); EventSystem.current.SetSelectedGameObject(currentSelected);
} }
@ -106,9 +107,7 @@ namespace NEG.UI.UnityUi
for (var current = result.gameObject.transform; for (var current = result.gameObject.transform;
current != null; current != null;
current = current.parent) current = current.parent)
{
ExecuteEvents.Execute(current.gameObject, data, ExecuteEvents.pointerEnterHandler); ExecuteEvents.Execute(current.gameObject, data, ExecuteEvents.pointerEnterHandler);
} }
} }
} }
}

View File

@ -6,7 +6,6 @@ using NEG.UI.UnityUi.Popup;
using NEG.UI.UnityUi.Window; using NEG.UI.UnityUi.Window;
using NEG.Utils; using NEG.Utils;
using System; using System;
using System.Collections.Generic;
using UnityEngine; using UnityEngine;
using UnityEngine.Assertions; using UnityEngine.Assertions;
using UnityEngine.EventSystems; using UnityEngine.EventSystems;
@ -19,24 +18,21 @@ namespace NEG.UI.UnityUi
/// Implements ui using UnityUI and Unity Event System with New Input System. /// Implements ui using UnityUI and Unity Event System with New Input System.
/// <para>You have to provide prefabs within resources:</para> /// <para>You have to provide prefabs within resources:</para>
/// <para> - UI/PopupCanvas - prefab with canvas to create popups (will be created on every scene)</para> /// <para> - UI/PopupCanvas - prefab with canvas to create popups (will be created on every scene)</para>
/// <para> - UI/DefaultPopupPrefab - prefab of default popup with 2 options (has to have <see cref="MonoDefaultPopup"/> component)</para> /// <para>
/// - UI/DefaultPopupPrefab - prefab of default popup with 2 options (has to have
/// <see cref="MonoDefaultPopup" /> component)
/// </para>
/// NEG_UI_DISABLE_WARNING_DEFAULT_SELECTION /// NEG_UI_DISABLE_WARNING_DEFAULT_SELECTION
/// </summary> /// </summary>
public class MonoUiManager : UiManager, IDisposable public class MonoUiManager : UiManager, IDisposable
{ {
//TODO: use default unity selection private readonly GameObject canvasPrefab;
//TODO: window snaping to slots
public static new MonoUiManager Instance { get; private set; }
public ButtonSettings DefaultUiSettings { get; }
public KeyBasedFactory<string, ButtonElementBehaviour> BehavioursFactory { get; private set; }
//TODO: editor to auto add slots, buttons //TODO: editor to auto add slots, buttons
private readonly MonoDefaultPopup defaultPopupPrefab; private readonly MonoDefaultPopup defaultPopupPrefab;
private readonly GameObject canvasPrefab;
private UiInputModule inputModule; private readonly UiInputModule inputModule;
public MonoUiManager(IArea startArea, Type inputModuleType, ButtonSettings defaultUiSettings) : base(startArea) public MonoUiManager(IArea startArea, Type inputModuleType, ButtonSettings defaultUiSettings) : base(startArea)
{ {
@ -45,8 +41,10 @@ namespace NEG.UI.UnityUi
var popupCanvas = Resources.Load<GameObject>("UI/PopupCanvas"); var popupCanvas = Resources.Load<GameObject>("UI/PopupCanvas");
var defaultPopup = Resources.Load<GameObject>("UI/DefaultPopupPrefab"); var defaultPopup = Resources.Load<GameObject>("UI/DefaultPopupPrefab");
Assert.IsNotNull(popupCanvas,"No canvas prefab was provided. Please check MonoUiManager class documentation"); Assert.IsNotNull(popupCanvas,
Assert.IsNotNull(defaultPopup,"No popup prefab was provided. Please check MonoUiManager class documentation"); "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<Canvas>()); Assert.IsNotNull(popupCanvas.GetComponent<Canvas>());
Assert.IsNotNull(defaultPopup.GetComponent<MonoDefaultPopup>()); Assert.IsNotNull(defaultPopup.GetComponent<MonoDefaultPopup>());
@ -64,6 +62,13 @@ namespace NEG.UI.UnityUi
DefaultUiSettings = defaultUiSettings; 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<string, ButtonElementBehaviour> BehavioursFactory { get; }
public override void Dispose() public override void Dispose()
{ {
base.Dispose(); base.Dispose();
@ -76,7 +81,8 @@ namespace NEG.UI.UnityUi
if (inputModule.CurrentSelectionSource != SelectionSource.Direction) if (inputModule.CurrentSelectionSource != SelectionSource.Direction)
return; 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; return;

View File

@ -16,10 +16,7 @@ namespace NEG.UI.UnityUi.Popup
public void SetContent(string title, string content, List<(string, Action)> options) public void SetContent(string title, string content, List<(string, Action)> options)
{ {
foreach (Transform child in buttonsParent) foreach (Transform child in buttonsParent) Destroy(child.gameObject);
{
Destroy(child.gameObject);
}
titleText.text = title; titleText.text = title;
contentText.text = content; contentText.text = content;

View File

@ -6,9 +6,8 @@ namespace NEG.UI.UnityUi.Popup
{ {
public class MonoPopup : MonoBehaviour, IPopup public class MonoPopup : MonoBehaviour, IPopup
{ {
public event Action<PopupData> OnPopupClosed;
protected PopupData data; protected PopupData data;
public event Action<PopupData> OnPopupClosed;
public virtual void Show(PopupData data) public virtual void Show(PopupData data)
{ {
@ -25,6 +24,5 @@ namespace NEG.UI.UnityUi.Popup
OnPopupClosed?.Invoke(data); OnPopupClosed?.Invoke(data);
} }
} }
} }

View File

@ -7,7 +7,7 @@ namespace NEG.UI.UnityUi.Window
{ {
public class CloseWindowOnBack : MonoController 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) protected override void OnBackUsed(IControllable.BackUsed backUsed)
{ {

View File

@ -1,6 +1,4 @@
using NEG.UI.Area; using NEG.UI.UnityUi.WindowSlot;
using NEG.UI.UnityUi.Buttons;
using NEG.UI.UnityUi.WindowSlot;
using NEG.UI.Window; using NEG.UI.Window;
using NEG.UI.WindowSlot; using NEG.UI.WindowSlot;
using NegUtils.NEG.UI; using NegUtils.NEG.UI;
@ -8,30 +6,44 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using UnityEngine; using UnityEngine;
using UnityEngine.EventSystems; using UnityEngine.EventSystems;
using UnityEngine.Serialization;
namespace NEG.UI.UnityUi.Window namespace NEG.UI.UnityUi.Window
{ {
[DefaultExecutionOrder(10)] [DefaultExecutionOrder(10)]
public class MonoWindow : MonoBehaviour, IWindow public class MonoWindow : MonoBehaviour, IWindow
{ {
public event Action<object> OnOpened; [SerializeField] private List<MonoWindowSlot> windowSlots;
public event Action OnClosed;
public event Action<IControllable.BackUsed> OnBackUsed;
public IEnumerable<IWindowSlot> AvailableSlots => windowSlots; [SerializeField] private GameObject defaultSelectedItem;
public IWindowSlot Parent { get; private set; }
public bool IsMainWindow { get; private set; } public bool IsMainWindow { get; }
public bool IsOpened { get; protected set; } public bool IsOpened { get; protected set; }
private IWindowSlot DefaultWindowSlot => windowSlots[0]; private IWindowSlot DefaultWindowSlot => windowSlots[0];
public GameObject DefaultSelectedItem => defaultSelectedItem; public GameObject DefaultSelectedItem => defaultSelectedItem;
[SerializeField] private List<MonoWindowSlot> windowSlots; private void Awake() => ((IWindow)this).SetHiddenState();
[SerializeField] private GameObject defaultSelectedItem; 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<object> OnOpened;
public event Action OnClosed;
public event Action<IControllable.BackUsed> OnBackUsed;
public IEnumerable<IWindowSlot> AvailableSlots => windowSlots;
public IWindowSlot Parent { get; private set; }
public void SetOpenedState(IWindowSlot parentSlot, object data) public void SetOpenedState(IWindowSlot parentSlot, object data)
{ {
@ -58,28 +70,10 @@ namespace NEG.UI.UnityUi.Window
public void SeVisibleState() => gameObject.SetActive(true); 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 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 TryUseBack(ref IControllable.BackUsed backUsed) => OnBackUsed?.Invoke(backUsed);
public void SetDefaultSelectedItem(GameObject item) => defaultSelectedItem = item;
} }
} }

View File

@ -1,22 +1,18 @@
using KBCore.Refs; using NEG.UI.Window;
using NEG.UI.Area;
using NEG.UI.Window;
using NEG.UI.WindowSlot; using NEG.UI.WindowSlot;
using System;
using UnityEngine;
using TNRD; using TNRD;
using UnityEngine;
namespace NEG.UI.UnityUi.WindowSlot namespace NEG.UI.UnityUi.WindowSlot
{ {
public abstract class MonoWindowSlot : MonoBehaviour, IWindowSlot public abstract class MonoWindowSlot : MonoBehaviour, IWindowSlot
{ {
[SerializeField] private SerializableInterface<ISlotsHolder> slotsHolder;
[field: SerializeField] public bool OpenWindowAsMain { get; private set; } [field: SerializeField] public bool OpenWindowAsMain { get; private set; }
public ISlotsHolder ParentHolder => slotsHolder.Value; public ISlotsHolder ParentHolder => slotsHolder.Value;
public abstract void AttachWindow(IWindow window, object data); public abstract void AttachWindow(IWindow window, object data);
public abstract void DetachWindow(IWindow window); public abstract void DetachWindow(IWindow window);
public abstract void CloseAllWindows(); public abstract void CloseAllWindows();
[SerializeField] private SerializableInterface<ISlotsHolder> slotsHolder;
} }
} }

View File

@ -1,11 +1,12 @@
using NEG.UI.UnityUi.WindowSlot; using NEG.UI.UnityUi.WindowSlot;
using NEG.UI.Window; using NEG.UI.Window;
using UnityEngine;
namespace NEG.UI.WindowSlot namespace NEG.UI.WindowSlot
{ {
public class SingleWindowSlot : MonoWindowSlot public class SingleWindowSlot : MonoWindowSlot
{ {
private IWindow currentWindow;
public IWindow CurrentWindow public IWindow CurrentWindow
{ {
get => currentWindow; get => currentWindow;
@ -16,8 +17,6 @@ namespace NEG.UI.WindowSlot
} }
} }
private IWindow currentWindow;
public override void AttachWindow(IWindow window, object data) public override void AttachWindow(IWindow window, object data)
{ {
CurrentWindow = window; CurrentWindow = window;

View File

@ -3,13 +3,16 @@ using NEG.UI.UnityUi.Window;
using NEG.UI.UnityUi.WindowSlot; using NEG.UI.UnityUi.WindowSlot;
using NEG.UI.Window; using NEG.UI.Window;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using UnityEngine.EventSystems; using UnityEngine.EventSystems;
namespace NegUtils.NEG.UI.UnityUi.WindowSlot namespace NegUtils.NEG.UI.UnityUi.WindowSlot
{ {
public class SingleWindowSlotWithHistory : MonoWindowSlot public class SingleWindowSlotWithHistory : MonoWindowSlot
{ {
private readonly List<IWindow> windowsHistory = new();
private IWindow currentWindow;
public IWindow CurrentWindow public IWindow CurrentWindow
{ {
get => currentWindow; get => currentWindow;
@ -27,10 +30,6 @@ namespace NegUtils.NEG.UI.UnityUi.WindowSlot
} }
} }
private IWindow currentWindow;
private readonly List<IWindow> windowsHistory = new List<IWindow>();
public override void AttachWindow(IWindow window, object data) public override void AttachWindow(IWindow window, object data)
{ {
CurrentWindow = window; CurrentWindow = window;
@ -50,13 +49,11 @@ namespace NegUtils.NEG.UI.UnityUi.WindowSlot
UiManager.Instance.MainWindowClosed(window); UiManager.Instance.MainWindowClosed(window);
EventSystem.current.SetSelectedGameObject(((MonoWindow)currentWindow).DefaultSelectedItem); EventSystem.current.SetSelectedGameObject(((MonoWindow)currentWindow).DefaultSelectedItem);
} }
public override void CloseAllWindows() public override void CloseAllWindows()
{ {
currentWindow = null; currentWindow = null;
foreach (var window in windowsHistory) foreach (var window in windowsHistory) window.SetClosedState();
{
window.SetClosedState();
}
windowsHistory.Clear(); windowsHistory.Clear();
} }
} }

View File

@ -1,5 +1,4 @@
using JetBrains.Annotations; using NEG.UI.Area;
using NEG.UI.Area;
using NEG.UI.WindowSlot; using NEG.UI.WindowSlot;
using NegUtils.NEG.UI; using NegUtils.NEG.UI;
using UnityEngine; using UnityEngine;
@ -73,14 +72,16 @@ namespace NEG.UI.Window
{ {
if (windowToOpen == null) if (windowToOpen == null)
{ {
Debug.LogError($"Window to open cannot be null"); Debug.LogError("Window to open cannot be null");
return; return;
} }
window.OpenWindow(windowToOpen, data); window.OpenWindow(windowToOpen, data);
} }
/// <summary> /// <summary>
/// Open window as child of provided window. If <typeparamref name="parentWindow"/> is null, as child of current main window in <see cref="UiManager"/>. If there is no main window, open on current area. /// Open window as child of provided window. If <typeparamref name="parentWindow" /> is null, as child of current main
/// window in <see cref="UiManager" />. If there is no main window, open on current area.
/// </summary> /// </summary>
/// <param name="window">window to open</param> /// <param name="window">window to open</param>
/// <param name="parentWindow">parent window</param> /// <param name="parentWindow">parent window</param>

View File

@ -16,10 +16,7 @@ namespace NEG.UI.WindowSlot
void CloseAllWindows() void CloseAllWindows()
{ {
foreach (var slot in AvailableSlots) foreach (var slot in AvailableSlots) slot.CloseAllWindows();
{
slot.CloseAllWindows();
}
} }
} }
} }

View File

@ -1,5 +1,4 @@
using NEG.UI.Area; using NEG.UI.Window;
using NEG.UI.Window;
namespace NEG.UI.WindowSlot namespace NEG.UI.WindowSlot
{ {

View File

@ -1,4 +1,6 @@
using System;
using UnityEngine; using UnityEngine;
/// <summary> /// <summary>
/// Attribute that require implementation of the provided interface. /// Attribute that require implementation of the provided interface.
/// </summary> /// </summary>
@ -7,15 +9,16 @@ namespace NEG.Utils
{ {
public class RequireInterfaceAttribute : PropertyAttribute public class RequireInterfaceAttribute : PropertyAttribute
{ {
// Interface type.
public System.Type requiredType { get; private set; }
/// <summary> /// <summary>
/// Requiring implementation of the <see cref="T:RequireInterfaceAttribute" /> interface. /// Requiring implementation of the <see cref="T:RequireInterfaceAttribute" /> interface.
/// </summary> /// </summary>
/// <param name="type">Interface type.</param> /// <param name="type">Interface type.</param>
public RequireInterfaceAttribute(System.Type type) public RequireInterfaceAttribute(Type type)
{ {
requiredType = type; requiredType = type;
} }
// Interface type.
public Type requiredType { get; private set; }
} }
} }

View File

@ -5,12 +5,6 @@ namespace NEG.Utils.Timing
{ {
public class AutoTimeMachine public class AutoTimeMachine
{ {
[PublicAPI]
public double Interval { get; set; }
[PublicAPI]
public Action Action { get; }
private readonly TimeMachine machine; private readonly TimeMachine machine;
public AutoTimeMachine(Action action, double interval) public AutoTimeMachine(Action action, double interval)
@ -20,6 +14,10 @@ namespace NEG.Utils.Timing
machine = new TimeMachine(); machine = new TimeMachine();
} }
[PublicAPI] public double Interval { get; set; }
[PublicAPI] public Action Action { get; }
/// <summary> /// <summary>
/// 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
/// </summary> /// </summary>
@ -28,10 +26,7 @@ namespace NEG.Utils.Timing
{ {
machine.Accumulate(time); machine.Accumulate(time);
int rolls = machine.RetrieveAll(Interval); int rolls = machine.RetrieveAll(Interval);
for (int i = 0; i < rolls; i++) for (int i = 0; i < rolls; i++) Action();
{
Action();
}
} }
} }
} }

View File

@ -31,6 +31,7 @@ namespace NEG.Utils.Timing
timeInternal = 0; timeInternal = 0;
return timeRetrieved; return timeRetrieved;
} }
double timeLeft = timeInternal - maxTime; double timeLeft = timeInternal - maxTime;
timeInternal = Math.Max(timeLeft, 0); timeInternal = Math.Max(timeLeft, 0);
return Math.Min(maxTime + timeLeft, maxTime); return Math.Min(maxTime + timeLeft, maxTime);
@ -38,7 +39,8 @@ namespace NEG.Utils.Timing
/// <summary> /// <summary>
/// Attempts to retrieves given amount of time from the TimeMachine <br /> /// Attempts to retrieves given amount of time from the TimeMachine <br />
/// If there is enough <paramref name="time"/> accumulated in this machine subtracts that amount and returns true, otherwise returns false /// If there is enough <paramref name="time" /> accumulated in this machine subtracts that amount and returns true,
/// otherwise returns false
/// </summary> /// </summary>
/// <param name="time"></param> /// <param name="time"></param>
public bool TryRetrieve(double time) public bool TryRetrieve(double time)
@ -50,7 +52,8 @@ namespace NEG.Utils.Timing
} }
/// <summary> /// <summary>
/// Result is equivalent to calling <see cref="TryRetrieve(double)"/> as many times as possible, but is faster for larger <paramref name="limit"/> values /// Result is equivalent to calling <see cref="TryRetrieve(double)" /> as many times as possible, but is faster for
/// larger <paramref name="limit" /> values
/// </summary> /// </summary>
/// <param name="interval">Single unit of warp time, must be positive</param> /// <param name="interval">Single unit of warp time, must be positive</param>
/// <param name="limit">Maximum amount of warps, must be positive</param> /// <param name="limit">Maximum amount of warps, must be positive</param>

View File

@ -1,5 +1,4 @@
using System.Collections; using UnityEngine;
using UnityEngine;
namespace NEG.Utils.UiToolkits namespace NEG.Utils.UiToolkits
{ {

View File

@ -4,12 +4,10 @@ namespace NEG.Utils.UiToolkits
{ {
public class MultiSelectChipItem public class MultiSelectChipItem
{ {
public VisualElement VisualElement { get; }
public IMultiSelectChipItem ChipItem { get; }
private readonly MultiSelectChips parent; private readonly MultiSelectChips parent;
public MultiSelectChipItem(VisualElement visualElement, IMultiSelectChipItem element, MultiSelectChips multiSelectChips) public MultiSelectChipItem(VisualElement visualElement, IMultiSelectChipItem element,
MultiSelectChips multiSelectChips)
{ {
VisualElement = visualElement; VisualElement = visualElement;
ChipItem = element; ChipItem = element;
@ -18,5 +16,8 @@ namespace NEG.Utils.UiToolkits
visualElement.Q<VisualElement>("Color").style.backgroundColor = element.Color; visualElement.Q<VisualElement>("Color").style.backgroundColor = element.Color;
visualElement.Q<Button>("RemoveBtn").clicked += () => parent.TryRemoveItem(element); visualElement.Q<Button>("RemoveBtn").clicked += () => parent.TryRemoveItem(element);
} }
public VisualElement VisualElement { get; }
public IMultiSelectChipItem ChipItem { get; }
} }
} }

View File

@ -1,8 +1,7 @@
using System;
using System.Collections.Generic;
using UnityEngine; using UnityEngine;
using UnityEngine.UIElements; using UnityEngine.UIElements;
using System.Collections.Generic;
using System;
using System.IO;
#if UNITY_EDITOR #if UNITY_EDITOR
using UnityEditor; using UnityEditor;
#endif #endif
@ -11,8 +10,30 @@ namespace NEG.Utils.UiToolkits
{ {
public class MultiSelectChips : VisualElement public class MultiSelectChips : VisualElement
{ {
public event Action<IMultiSelectChipItem> OnTryingToRemoveItem; private readonly List<MultiSelectChipItem> spawnedItems = new();
public event Action<Rect> OnTryingToAddItem;
private readonly VisualTreeAsset itemPrefab;
private ICollection<IMultiSelectChipItem> itemsSource;
private Label label;
private VisualElement realItemsParent;
public MultiSelectChips()
{
#if UNITY_EDITOR
string path =
AssetDatabase.GUIDToAssetPath(AssetDatabase.FindAssets($"t:Script {nameof(MultiSelectChips)}")[0]);
path = path.Remove(path.LastIndexOf('/'));
SetVisuals(AssetDatabase.LoadAssetAtPath<VisualTreeAsset>($"{path}/Resources/MultiSelectChips.uxml"));
itemPrefab = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>($"{path}/Resources/MultiSelectChipItem.uxml");
#else
SetVisuals(Resources.Load<VisualTreeAsset>("MultiSelectChips.uxml"));
itemPrefab = Resources.Load<VisualTreeAsset>("MultiSelectChipItem.uxml");
#endif
}
public string LabelText public string LabelText
{ {
@ -21,10 +42,7 @@ namespace NEG.Utils.UiToolkits
{ {
if (!string.IsNullOrEmpty(value)) if (!string.IsNullOrEmpty(value))
{ {
if (label == null) if (label == null) InitLabel();
{
InitLabel();
}
label.text = value; label.text = value;
} }
@ -47,53 +65,8 @@ namespace NEG.Utils.UiToolkits
} }
} }
private Label label; public event Action<IMultiSelectChipItem> OnTryingToRemoveItem;
public event Action<Rect> OnTryingToAddItem;
private VisualTreeAsset itemPrefab;
private ICollection<IMultiSelectChipItem> itemsSource;
private readonly List<MultiSelectChipItem> spawnedItems = new();
private VisualElement realItemsParent;
public new class UxmlFactory : UxmlFactory<MultiSelectChips, UxmlTraits>
{
}
public new class UxmlTraits : VisualElement.UxmlTraits
{
private readonly UxmlStringAttributeDescription label;
public UxmlTraits()
{
label = new()
{
name = "label"
};
}
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
((MultiSelectChips)ve).LabelText = label.GetValueFromBag(bag, cc);
}
}
public MultiSelectChips() : base()
{
#if UNITY_EDITOR
string path = AssetDatabase.GUIDToAssetPath(AssetDatabase.FindAssets($"t:Script {nameof(MultiSelectChips)}")[0]);
path = path.Remove(path.LastIndexOf('/'));
SetVisuals(AssetDatabase.LoadAssetAtPath<VisualTreeAsset>($"{path}/Resources/MultiSelectChips.uxml"));
itemPrefab = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>($"{path}/Resources/MultiSelectChipItem.uxml");
#else
SetVisuals(Resources.Load<VisualTreeAsset>("MultiSelectChips.uxml"));
itemPrefab = Resources.Load<VisualTreeAsset>("MultiSelectChipItem.uxml");
#endif
}
public void UpdateItems() public void UpdateItems()
{ {
@ -102,7 +75,7 @@ namespace NEG.Utils.UiToolkits
var itemsToDestroy = new List<MultiSelectChipItem>(spawnedItems); var itemsToDestroy = new List<MultiSelectChipItem>(spawnedItems);
itemsToDestroy.RemoveAll((x) => itemsSource.Contains(x.ChipItem)); itemsToDestroy.RemoveAll(x => itemsSource.Contains(x.ChipItem));
foreach (var item in itemsToDestroy) foreach (var item in itemsToDestroy)
{ {
@ -113,10 +86,8 @@ namespace NEG.Utils.UiToolkits
List<IMultiSelectChipItem> itemsToAdd = new(itemsSource); List<IMultiSelectChipItem> itemsToAdd = new(itemsSource);
foreach (var item in spawnedItems) foreach (var item in spawnedItems)
{
if (itemsToAdd.Contains(item.ChipItem)) if (itemsToAdd.Contains(item.ChipItem))
itemsToAdd.Remove(item.ChipItem); itemsToAdd.Remove(item.ChipItem);
}
foreach (var item in itemsToAdd) foreach (var item in itemsToAdd)
{ {
@ -130,10 +101,7 @@ namespace NEG.Utils.UiToolkits
private void InitLabel() private void InitLabel()
{ {
label = new Label() label = new Label { pickingMode = PickingMode.Ignore };
{
pickingMode = PickingMode.Ignore
};
Insert(0, label); Insert(0, label);
} }
@ -148,5 +116,25 @@ namespace NEG.Utils.UiToolkits
realItemsParent = button.parent; realItemsParent = button.parent;
} }
public new class UxmlFactory : UxmlFactory<MultiSelectChips, UxmlTraits>
{
}
public new class UxmlTraits : VisualElement.UxmlTraits
{
private readonly UxmlStringAttributeDescription label;
public UxmlTraits()
{
label = new UxmlStringAttributeDescription { name = "label" };
}
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
((MultiSelectChips)ve).LabelText = label.GetValueFromBag(bag, cc);
}
}
} }
} }

View File

@ -1,7 +1,12 @@
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../../../../UIElementsSchema/UIElements.xsd" editor-extension-mode="False"> <ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements"
<ui:VisualElement name="VisualElement" class="unity-button" style="min-height: 21px; flex-shrink: 1; flex-direction: row; flex-wrap: wrap; align-items: center;"> xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements"
<ui:VisualElement name="Color" style="min-height: 15px; min-width: 15px; border-top-left-radius: 22px; border-bottom-left-radius: 22px; border-top-right-radius: 22px; border-bottom-right-radius: 22px; border-left-width: 0; border-right-width: 0; border-top-width: 0; border-bottom-width: 0; border-left-color: rgba(0, 0, 125, 255); border-right-color: rgba(0, 0, 125, 255); border-top-color: rgba(0, 0, 125, 255); border-bottom-color: rgba(0, 0, 125, 255); background-color: rgba(255, 0, 0, 255); max-height: 15px; justify-content: center; align-items: center;" /> noNamespaceSchemaLocation="../../../../../UIElementsSchema/UIElements.xsd" editor-extension-mode="False">
<ui:Label text="Name" display-tooltip-when-elided="true" name="Name" style="padding-left: 7px; padding-right: 5px;" /> <ui:VisualElement name="VisualElement" class="unity-button"
style="min-height: 21px; flex-shrink: 1; flex-direction: row; flex-wrap: wrap; align-items: center;">
<ui:VisualElement name="Color"
style="min-height: 15px; min-width: 15px; border-top-left-radius: 22px; border-bottom-left-radius: 22px; border-top-right-radius: 22px; border-bottom-right-radius: 22px; border-left-width: 0; border-right-width: 0; border-top-width: 0; border-bottom-width: 0; border-left-color: rgba(0, 0, 125, 255); border-right-color: rgba(0, 0, 125, 255); border-top-color: rgba(0, 0, 125, 255); border-bottom-color: rgba(0, 0, 125, 255); background-color: rgba(255, 0, 0, 255); max-height: 15px; justify-content: center; align-items: center;"/>
<ui:Label text="Name" display-tooltip-when-elided="true" name="Name"
style="padding-left: 7px; padding-right: 5px;"/>
<ui:Button text="X" display-tooltip-when-elided="true" name="RemoveBtn"/> <ui:Button text="X" display-tooltip-when-elided="true" name="RemoveBtn"/>
</ui:VisualElement> </ui:VisualElement>
</ui:UXML> </ui:UXML>

View File

@ -1,4 +1,6 @@
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../../../../UIElementsSchema/UIElements.xsd" editor-extension-mode="False"> <ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements"
xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements"
noNamespaceSchemaLocation="../../../../../UIElementsSchema/UIElements.xsd" editor-extension-mode="False">
<ui:VisualElement style="flex-direction: row; flex-wrap: wrap;"> <ui:VisualElement style="flex-direction: row; flex-wrap: wrap;">
<ui:Button text="+" display-tooltip-when-elided="true" name="AddItem"/> <ui:Button text="+" display-tooltip-when-elided="true" name="AddItem"/>
</ui:VisualElement> </ui:VisualElement>

View File

@ -1,5 +1,5 @@
using UnityEngine; using JetBrains.Annotations;
using JetBrains.Annotations; using UnityEngine;
namespace NEG.Utils namespace NEG.Utils
{ {