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.SceneManagement;
namespace NEG.Utils
{
@ -10,4 +9,3 @@ namespace NEG.Utils
#endif
}
}

View File

@ -5,7 +5,8 @@ namespace NEG.Utils.Collections
public static class DictionaryExtensions
{
/// <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>
/// <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)
@ -15,24 +16,20 @@ namespace NEG.Utils.Collections
dict[key] = value;
return false;
}
else
{
dict.Add(key, value);
return true;
}
dict.Add(key, value);
return true;
}
/// <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>
/// <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)
{
if (dict.TryGetValue(key, out V value))
{
return value;
}
if (dict.TryGetValue(key, out var value)) return value;
dict.Add(key, defaultValue);
return defaultValue;

View File

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

View File

@ -1,8 +1,8 @@
using System.Diagnostics;
using System.Linq;
using UnityEngine;
using UnityEditor;
using UnityEditor.Build.Player;
using UnityEditor.Build;
using UnityEngine;
using Debug = UnityEngine.Debug;
public static class BuildingUtils
@ -12,9 +12,9 @@ public static class BuildingUtils
[MenuItem("Tools/PrepareForBuild", priority = -10)]
public static void PrepareForBuild()
{
var namedBuildTarget = UnityEditor.Build.NamedBuildTarget.FromBuildTargetGroup(
var namedBuildTarget = NamedBuildTarget.FromBuildTargetGroup(
BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget));
var args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget);
string[] args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget);
var argsList = args.ToList();
argsList.Remove(SteamBuildDefine);
PlayerSettings.SetScriptingDefineSymbols(namedBuildTarget, argsList.ToArray());
@ -25,9 +25,9 @@ public static class BuildingUtils
{
PrepareForBuild();
var namedBuildTarget = UnityEditor.Build.NamedBuildTarget.FromBuildTargetGroup(
var namedBuildTarget = NamedBuildTarget.FromBuildTargetGroup(
BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget));
var args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget);
string[] args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget);
var argsList = args.ToList();
argsList.Add(SteamBuildDefine);
PlayerSettings.SetScriptingDefineSymbols(namedBuildTarget, argsList.ToArray());
@ -37,7 +37,7 @@ public static class BuildingUtils
[MenuItem("Tools/Build/Steam/Release")]
public static void SteamRelease()
{
if(!CanBuild())
if (!CanBuild())
return;
IncreaseBuildNumber();
@ -48,7 +48,7 @@ public static class BuildingUtils
[MenuItem("Tools/Build/Steam/Development")]
public static void SteamDevelopment()
{
if(!CanBuild())
if (!CanBuild())
return;
IncreaseBuildNumber();
@ -60,7 +60,7 @@ public static class BuildingUtils
[MenuItem("Tools/Build/Steam/Demo")]
public static void SteamDemo()
{
if(!CanBuild())
if (!CanBuild())
return;
IncreaseBuildNumber();
@ -71,7 +71,7 @@ public static class BuildingUtils
[MenuItem("Tools/Build/All Release")]
public static void BuildRelease()
{
if(!CanBuild())
if (!CanBuild())
return;
BuildWindowsRelease();
BuildLinuxRelease();
@ -80,7 +80,7 @@ public static class BuildingUtils
[MenuItem("Tools/Build/All Development")]
public static void BuildDevelopment()
{
if(!CanBuild())
if (!CanBuild())
return;
BuildWindowsDevelopment();
}
@ -88,16 +88,16 @@ public static class BuildingUtils
[MenuItem("Tools/Build/All Demo")]
public static void BuildDemo()
{
if(!CanBuild())
if (!CanBuild())
return;
BuildWindows(true, new[] {"DEMO"});
BuildLinux(true, new[] {"DEMO"});
BuildWindows(true, new[] { "DEMO" });
BuildLinux(true, new[] { "DEMO" });
}
[MenuItem("Tools/Build/Platform/Windows/x64-Development")]
public static void BuildWindowsDevelopment()
{
if(!CanBuild())
if (!CanBuild())
return;
BuildWindows(false);
}
@ -105,7 +105,7 @@ public static class BuildingUtils
[MenuItem("Tools/Build/Platform/Windows/x64-Release")]
public static void BuildWindowsRelease()
{
if(!CanBuild())
if (!CanBuild())
return;
BuildWindows(true);
}
@ -113,7 +113,7 @@ public static class BuildingUtils
[MenuItem("Tools/Build/Platform/Linux/x64-Release")]
public static void BuildLinuxRelease()
{
if(!CanBuild())
if (!CanBuild())
return;
BuildLinux(true);
}
@ -128,9 +128,7 @@ public static class BuildingUtils
var buildPlayerOptions = new BuildPlayerOptions { scenes = new string[EditorBuildSettings.scenes.Length] };
for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)
{
buildPlayerOptions.scenes[i] = EditorBuildSettings.scenes[i].path;
}
buildPlayerOptions.target = BuildTarget.Android;
buildPlayerOptions.options = BuildOptions.None;
@ -143,9 +141,7 @@ public static class BuildingUtils
{
var buildPlayerOptions = new BuildPlayerOptions { scenes = new string[EditorBuildSettings.scenes.Length] };
for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)
{
buildPlayerOptions.scenes[i] = EditorBuildSettings.scenes[i].path;
}
buildPlayerOptions.extraScriptingDefines = additionalDefines;
@ -160,9 +156,7 @@ public static class BuildingUtils
{
var buildPlayerOptions = new BuildPlayerOptions { scenes = new string[EditorBuildSettings.scenes.Length] };
for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)
{
buildPlayerOptions.scenes[i] = EditorBuildSettings.scenes[i].path;
}
buildPlayerOptions.extraScriptingDefines = additionalDefines;
@ -175,28 +169,29 @@ public static class BuildingUtils
private static void IncreaseBuildNumber()
{
string[] versionParts = PlayerSettings.bundleVersion.Split('.');
if (versionParts.Length != 3 || !int.TryParse(versionParts[2], out int version)) {
string[] versionParts = PlayerSettings.bundleVersion.Split('.');
if (versionParts.Length != 3 || !int.TryParse(versionParts[2], out int version))
{
Debug.LogError("IncreaseBuildNumber failed to update version " + PlayerSettings.bundleVersion);
return;
}
versionParts[2] = (version + 1).ToString();
PlayerSettings.bundleVersion = string.Join(".", versionParts);
}
private static void UploadSteam(bool demo = false)
{
string command = $"cd {Application.dataPath}/../../{Application.productName}-Steam/ContentBuilder && push_build.bat";
string command =
$"cd {Application.dataPath}/../../{Application.productName}-Steam/ContentBuilder && push_build.bat";
if (demo)
{
command = $"cd {Application.dataPath}/../../{Application.productName}-Steam/ContentBuilder && push_demo.bat";
}
command =
$"cd {Application.dataPath}/../../{Application.productName}-Steam/ContentBuilder && push_demo.bat";
var processInfo = new ProcessStartInfo("cmd.exe", $"/c {command}")
{
CreateNoWindow = true,
UseShellExecute = false
};
{
CreateNoWindow = true, UseShellExecute = false
};
var process = Process.Start(processInfo);
process.WaitForExit();
Debug.Log(process.ExitCode);
@ -207,15 +202,16 @@ public static class BuildingUtils
{
if (CanBuildUtil())
return true;
Debug.LogError("Cannot build with defines set in project, please use PrepareForBuild and wait for scripts recompilation");
Debug.LogError(
"Cannot build with defines set in project, please use PrepareForBuild and wait for scripts recompilation");
return false;
}
private static bool CanBuildUtil()
{
var namedBuildTarget = UnityEditor.Build.NamedBuildTarget.FromBuildTargetGroup(
var namedBuildTarget = NamedBuildTarget.FromBuildTargetGroup(
BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget));
var args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget);
string[] args = PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget);
var argsList = args.ToList();
if (argsList.Contains(SteamBuildDefine))

View File

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

View File

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

View File

@ -9,6 +9,17 @@ namespace NegUtils.Editor
public class AssetPath
{
private readonly string filter;
private string path;
public AssetPath(string filter)
{
this.filter = filter;
TryFindPath();
}
public string Path
{
get
@ -20,16 +31,6 @@ namespace NegUtils.Editor
}
}
private string path;
private readonly string filter;
public AssetPath(string filter)
{
this.filter = filter;
TryFindPath();
}
private void TryFindPath()
{
string[] candidates = AssetDatabase.FindAssets(filter);

View File

@ -3,21 +3,16 @@ using UnityEngine;
public class GUIDToAssetPath : EditorWindow
{
string guid = "";
string path = "";
[MenuItem("Tools/GUIDToAssetPath")]
static void CreateWindow()
{
GUIDToAssetPath window = (GUIDToAssetPath)EditorWindow.GetWindowWithRect(typeof(GUIDToAssetPath), new Rect(0, 0, 400, 120));
}
private string guid = "";
private string path = "";
void OnGUI()
private void OnGUI()
{
GUILayout.Label("Enter guid");
guid = GUILayout.TextField(guid);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Get Asset Path",GUILayout.Width(120)))
if (GUILayout.Button("Get Asset Path", GUILayout.Width(120)))
path = GetAssetPath(guid);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
@ -29,7 +24,14 @@ public class GUIDToAssetPath : EditorWindow
GUILayout.EndHorizontal();
GUILayout.Label(path);
}
static string GetAssetPath(string guid)
[MenuItem("Tools/GUIDToAssetPath")]
private static void CreateWindow()
{
var window = (GUIDToAssetPath)GetWindowWithRect(typeof(GUIDToAssetPath), new Rect(0, 0, 400, 120));
}
private static string GetAssetPath(string guid)
{
guid = guid.Replace("-", "");

View File

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

View File

@ -1,18 +1,18 @@
{
"name": "NEG.Utils.Editor",
"rootNamespace": "",
"references": [
"GUID:3c4294719a93e3c4e831a9ff0c261e8a"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
"name": "NEG.Utils.Editor",
"rootNamespace": "",
"references": [
"GUID:3c4294719a93e3c4e831a9ff0c261e8a"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

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

View File

@ -1,5 +1,6 @@
using UnityEngine;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Drawer for the RequireInterface attribute.
/// </summary>
@ -10,7 +11,7 @@ namespace NEG.Utils
public class RequireInterfaceDrawer : PropertyDrawer
{
/// <summary>
/// Overrides GUI drawing for the attribute.
/// Overrides GUI drawing for the attribute.
/// </summary>
/// <param name="position">Position.</param>
/// <param name="property">Property.</param>
@ -21,11 +22,12 @@ namespace NEG.Utils
if (property.propertyType == SerializedPropertyType.ObjectReference)
{
// Get attribute parameters.
var requiredAttribute = this.attribute as RequireInterfaceAttribute;
var requiredAttribute = attribute as RequireInterfaceAttribute;
// Begin drawing property field.
EditorGUI.BeginProperty(position, label, property);
// Draw property field.
property.objectReferenceValue = EditorGUI.ObjectField(position, label, property.objectReferenceValue, requiredAttribute.requiredType, true);
property.objectReferenceValue = EditorGUI.ObjectField(position, label, property.objectReferenceValue,
requiredAttribute.requiredType, true);
// Finish drawing property field.
EditorGUI.EndProperty();
}

View File

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

View File

@ -1,19 +1,14 @@
using System;
using UnityEditor;
namespace NEG.Utils.Serialization
{
public static class SerializationExtentions
{
public static SerializedProperty FindAutoProperty(this SerializedObject @this, string name)
{
return @this.FindProperty(GetBackingFieldName(name));
}
public static SerializedProperty FindAutoProperty(this SerializedObject @this, string name) =>
@this.FindProperty(GetBackingFieldName(name));
public static SerializedProperty FindAutoPropertyRelative(this SerializedProperty @this, string name)
{
return @this.FindPropertyRelative(GetBackingFieldName(name));
}
public static SerializedProperty FindAutoPropertyRelative(this SerializedProperty @this, string name) =>
@this.FindPropertyRelative(GetBackingFieldName(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.SceneManagement;
using UnityEngine;
@ -17,13 +16,6 @@ namespace NegUtils.Editor
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
}
[MenuItem("Tools/Show Tools Window")]
private static void ShowWindow()
{
var window = GetWindow<ToolsWindowBase>();
window.Show();
}
protected virtual void OnGUI()
{
if (GUILayout.Button("Select Scene"))
@ -31,27 +23,25 @@ namespace NegUtils.Editor
bool startFromSceneIndex0 = EditorPrefs.GetBool("StartFromSceneIndex0");
bool newVal = GUILayout.Toggle(startFromSceneIndex0, "Start from scene with index 0 on start");
if (newVal != startFromSceneIndex0)
{
EditorPrefs.SetBool("StartFromSceneIndex0", newVal);
}
if (newVal != startFromSceneIndex0) EditorPrefs.SetBool("StartFromSceneIndex0", newVal);
if (!startFromSceneIndex0)
return;
bool goToCurrentScene = EditorPrefs.GetBool("GoToCurrentSceneAfterPlay");
newVal = GUILayout.Toggle(goToCurrentScene, "Go to current scene after play");
if (newVal != goToCurrentScene)
{
EditorPrefs.SetBool("GoToCurrentSceneAfterPlay", newVal);
}
if (newVal != goToCurrentScene) EditorPrefs.SetBool("GoToCurrentSceneAfterPlay", newVal);
bool goToFirstScene = EditorPrefs.GetBool("GoToFirstSceneAfterPlay");
newVal = GUILayout.Toggle(goToFirstScene, "Go to scene with index 1 after play");
if (newVal != goToFirstScene)
{
EditorPrefs.SetBool("GoToFirstSceneAfterPlay", newVal);
}
if (newVal != goToFirstScene) 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)
@ -71,19 +61,20 @@ namespace NegUtils.Editor
for (int i = 0; i < fileInfo.Length; i++)
{
string s = fileInfo[i];
menu.AddItem(new GUIContent(s.Remove(0, basePath.Length + 1).Remove(s.Length - basePath.Length - UnitySceneExtensionLength - 1 ,UnitySceneExtensionLength).Replace('\\', '/')), false, () => {
LoadScene(s);
});
menu.AddItem(
new GUIContent(s.Remove(0, basePath.Length + 1)
.Remove(s.Length - basePath.Length - UnitySceneExtensionLength - 1, UnitySceneExtensionLength)
.Replace('\\', '/')), false, () =>
{
LoadScene(s);
});
if(i == fileInfo.Length) continue;
if (i == fileInfo.Length) continue;
menu.AddSeparator("");
}
string[] dirInfo = Directory.GetDirectories(path);
foreach (string dir in dirInfo)
{
AddFiles(dir, basePath, menu);
}
foreach (string dir in dirInfo) AddFiles(dir, basePath, menu);
}
private static void LoadScene(string path)
@ -94,11 +85,11 @@ namespace NegUtils.Editor
private static void OnPlayModeStateChanged(PlayModeStateChange state)
{
switch(state)
switch (state)
{
case PlayModeStateChange.ExitingEditMode:
{
if(!EditorPrefs.GetBool("StartFromSceneIndex0"))
if (!EditorPrefs.GetBool("StartFromSceneIndex0"))
return;
EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo();
EditorPrefs.SetString("LastOpenedScenePath", EditorSceneManager.GetSceneManagerSetup()[0].path);
@ -107,7 +98,7 @@ namespace NegUtils.Editor
break;
case PlayModeStateChange.EnteredPlayMode:
{
if(!EditorPrefs.GetBool("StartFromSceneIndex0"))
if (!EditorPrefs.GetBool("StartFromSceneIndex0"))
return;
if (EditorPrefs.GetBool("GoToCurrentSceneAfterPlay"))
@ -119,13 +110,12 @@ namespace NegUtils.Editor
break;
case PlayModeStateChange.EnteredEditMode:
{
if(!EditorPrefs.GetBool("StartFromSceneIndex0"))
if (!EditorPrefs.GetBool("StartFromSceneIndex0"))
return;
EditorSceneManager.OpenScene(EditorPrefs.GetString("LastOpenedScenePath"));
}
break;
}
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -1,14 +1,16 @@
{
"name": "NEG.UI",
"rootNamespace": "",
"references": ["GUID:3c4294719a93e3c4e831a9ff0c261e8a"],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
"name": "NEG.UI",
"rootNamespace": "",
"references": [
"GUID:3c4294719a93e3c4e831a9ff0c261e8a"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

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

View File

@ -6,11 +6,14 @@ namespace NEG.UI.Popup
public interface IDefaultPopup : IPopup
{
/// <summary>
/// Sets content based on provided data.
/// Sets content based on provided data.
/// </summary>
/// <param name="title">popup title</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);
}
}

View File

@ -7,18 +7,18 @@ namespace NEG.UI.Popup
public interface IPopup
{
/// <summary>
/// Event to fire when popup is closed
/// Event to fire when popup is closed
/// </summary>
event Action<PopupData> OnPopupClosed;
/// <summary>
/// Show popup
/// Show popup
/// </summary>
/// <param name="data">data assigned to popup, used to give info that popup is closed</param>
public void Show(PopupData data);
/// <summary>
/// Close popup or mark as closed if not visible
/// Close popup or mark as closed if not visible
/// </summary>
/// <param name="silent">if true hide visually, without firing callbacks to properly close</param>
void Close(bool silent = false);

View File

@ -6,24 +6,10 @@ namespace NEG.UI.Popup
[PublicAPI]
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;
/// <summary>
/// PopupData constructor.
/// PopupData constructor.
/// </summary>
/// <param name="popup">attached to this data, can be used by different data instances</param>
public PopupData(IPopup popup)
@ -33,17 +19,31 @@ namespace NEG.UI.Popup
}
/// <summary>
/// Show popup and pass needed data.
/// 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>
/// Show popup and pass needed data.
/// </summary>
public virtual void Show() => popup.Show(this);
/// <summary>
/// Hide popup. Close visuals without firing events;
/// Hide popup. Close visuals without firing events;
/// </summary>
public virtual void Hide() => popup.Close(true);
/// <summary>
/// Invalidate popup, <see cref="UiManager"/> will automatically skip this popup
/// Invalidate popup, <see cref="UiManager" /> will automatically skip this popup
/// </summary>
public virtual void Invalidate()
{

View File

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

View File

@ -2,7 +2,6 @@ using JetBrains.Annotations;
using NEG.UI.Area;
using NEG.UI.Popup;
using NEG.UI.Window;
using NEG.Utils;
using NegUtils.NEG.UI;
using System;
using System.Collections.Generic;
@ -14,42 +13,17 @@ namespace NEG.UI
[PublicAPI]
public abstract class UiManager : IDisposable
{
public static UiManager Instance { get; protected set; }
/// <summary>
/// Current area shown on screen.
/// </summary>
public IArea CurrentArea
{
get => currentArea;
set
{
currentArea?.Close();
currentArea = value;
currentArea?.Open();
}
}
/// <summary>
/// Current window that is considered main (focused, lastly opened). Can be null.
/// </summary>
public IWindow CurrentMainWindow => mainWindows.LastOrDefault();
public PopupData CurrentPopup => currentShownPopup.data;
private IArea currentArea;
private (PopupData data, int priority) currentShownPopup;
protected IDefaultPopup currentDefaultPopup;
private PriorityQueue<PopupData, int> popupsToShow = new();
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)
@ -64,8 +38,36 @@ namespace NEG.UI
mainWindows = new List<IWindow>();
}
public static UiManager Instance { get; protected set; }
/// <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.
/// Current area shown on screen.
/// </summary>
public IArea CurrentArea
{
get => currentArea;
set
{
currentArea?.Close();
currentArea = value;
currentArea?.Open();
}
}
/// <summary>
/// Current window that is considered main (focused, lastly opened). Can be null.
/// </summary>
public IWindow CurrentMainWindow => mainWindows.LastOrDefault();
public PopupData CurrentPopup => currentShownPopup.data;
public virtual void Dispose() => Instance = null;
/// <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.
/// </summary>
/// <param name="title">popup title</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="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>
public PopupData ShowOkPopup(string title, string content, string okText = null, Action okPressed = null, int priority = 0, bool forceShow = false)
public PopupData ShowOkPopup(string title, string content, string okText = null, Action okPressed = null,
int priority = 0, bool forceShow = false)
{
var data = new DefaultPopupData(currentDefaultPopup, title, content,
new List<(string, Action)>() { (okText ?? localizedOk, okPressed) });
new List<(string, Action)> { (okText ?? localizedOk, okPressed) });
ShowPopup(data, priority, forceShow);
return data;
}
/// <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>
/// <param name="title">popup title</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="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>
public PopupData ShowYesNoPopup(string title, string content, string yesText = null, string noText = null, Action yesPressed = null, Action noPressed = null, int priority = 0, bool forceShow = false)
public PopupData ShowYesNoPopup(string title, string content, string yesText = null, string noText = null,
Action yesPressed = null, Action noPressed = null, int priority = 0, bool forceShow = false)
{
var data = new DefaultPopupData(currentDefaultPopup, title, content,
new List<(string, Action)>() { (yesText ?? localizedYes, yesPressed), (noText ?? localizedNo, noPressed) });
new List<(string, Action)>
{
(yesText ?? localizedYes, yesPressed), (noText ?? localizedNo, noPressed)
});
ShowPopup(data, priority, forceShow);
return data;
}
/// <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>
/// <param name="title">popup title</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="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>
public PopupData ShowPopup(string title, string content, List<(string, Action)> actions, int priority = 0, bool forceShow = false)
public PopupData ShowPopup(string title, string content, List<(string, Action)> actions, int priority = 0,
bool forceShow = false)
{
var data = new DefaultPopupData(currentDefaultPopup, title, content, actions);
ShowPopup(data, priority, forceShow);
@ -119,7 +129,7 @@ namespace NEG.UI
}
/// <summary>
/// Show popup if there is non other currently shown. Otherwise add current popup to ordered queue and show it later.
/// Show popup if there is non other currently shown. Otherwise add current popup to ordered queue and show it later.
/// </summary>
/// <param name="data">popup data object</param>
/// <param name="priority">priority of popup (lower number -> show first)</param>
@ -135,7 +145,7 @@ namespace NEG.UI
IControllable.BackUsed backUsed = new();
CurrentMainWindow?.TryUseBack(ref backUsed);
if(backUsed.Used)
if (backUsed.Used)
return;
CurrentArea.TryUseBack(ref backUsed);
}
@ -143,14 +153,12 @@ namespace NEG.UI
public void RefreshPopups()
{
if(currentShownPopup.data is { IsValid: true })
if (currentShownPopup.data is { IsValid: true })
return;
UpdatePopupsState(false);
}
public virtual void Dispose() => Instance = null;
public void SetMainWindow(IWindow window) => mainWindows.Add(window);
public void SetMainWindow(IWindow window) => mainWindows.Add(window);
public void MainWindowClosed(IWindow window) => mainWindows.Remove(window);
@ -160,10 +168,8 @@ namespace NEG.UI
protected void PopupClosed(PopupData data)
{
if (currentShownPopup.data != data)
{
//Debug.LogError("Popup was not shown");
return;
}
UpdatePopupsState(false);
}
@ -174,7 +180,7 @@ namespace NEG.UI
{
if (forceShow)
{
if(currentShownPopup.data != null && currentShownPopup.priority >= priority)
if (currentShownPopup.data != null && currentShownPopup.priority >= priority)
return;
popupsToShow.Enqueue(currentShownPopup.data, currentShownPopup.priority);
@ -184,11 +190,11 @@ namespace NEG.UI
while (popupsToShow.TryDequeue(out var d, out int p))
{
if(d == null)
if (d == null)
continue;
if(!d.IsValid)
if (!d.IsValid)
continue;
if(d == currentShownPopup.data)
if (d == currentShownPopup.data)
continue;
ShowPopup(d, p);
return;
@ -208,11 +214,10 @@ namespace NEG.UI
currentShownPopup.data.PopupClosedEvent -= PopupClosed;
currentShownPopup.data.Hide();
}
currentShownPopup = (data, priority);
data.Show();
data.PopupClosedEvent += PopupClosed;
}
}
}

View File

@ -10,7 +10,7 @@ namespace NEG.UI.Area
private void Start()
{
if(UiManager.Instance.CurrentMainWindow == null)
if (UiManager.Instance.CurrentMainWindow == null)
window.Open();
}
}

View File

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

View File

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

View File

@ -1,40 +1,19 @@
using System.Collections.Generic;
using UnityEngine;
using NEG.UI.Popup;
using NEG.UI.UnityUi.Window;
using NEG.UI.UnityUi.WindowSlot;
using NEG.UI.UnityUi.WindowSlot;
using NEG.UI.Window;
using NEG.UI.WindowSlot;
using NegUtils.NEG.UI;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace NEG.UI.Area
{
public class MonoArea : MonoBehaviour, IArea
{
public event Action<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 List<MonoWindowSlot> windowSlots;
public void Open()
{
gameObject.SetActive(true);
OnOpened?.Invoke(null);
}
public void Close(){
gameObject.SetActive(false);
OnClosed?.Invoke();
}
public void OpenWindow(IWindow window, object data = null) => DefaultWindowSlot.AttachWindow(window, data);
public IWindowSlot DefaultWindowSlot => windowSlots[0];
protected virtual void Awake()
{
@ -44,7 +23,7 @@ namespace NEG.UI.Area
private void Start()
{
if(!setAsDefaultArea)
if (!setAsDefaultArea)
Close();
}
@ -54,6 +33,26 @@ namespace NEG.UI.Area
UiManager.Instance.CurrentArea = null;
}
public event Action<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);
}
}

View File

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

View File

@ -1,5 +1,4 @@
using System;
using KBCore.Refs;
using KBCore.Refs;
using UnityEngine;
namespace NEG.UI.UnityUi.Buttons
@ -7,7 +6,7 @@ namespace NEG.UI.UnityUi.Buttons
[RequireComponent(typeof(BaseButton))]
public abstract class ButtonReaction : MonoBehaviour
{
[SerializeField, Self(Flag.Optional)] protected BaseButton button;
[SerializeField] [Self(Flag.Optional)] protected BaseButton button;
protected virtual void Awake() => button.OnButtonPressed += OnClicked;

View File

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

View File

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

View File

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

View File

@ -18,19 +18,19 @@ namespace NEG.UI.UnityUi.Buttons
switch (eventData.moveDir)
{
case MoveDirection.Left:
if(TryNavigate(eventData, leftOverride))
if (TryNavigate(eventData, leftOverride))
return;
break;
case MoveDirection.Up:
if(TryNavigate(eventData, upOverride))
if (TryNavigate(eventData, upOverride))
return;
break;
case MoveDirection.Right:
if(TryNavigate(eventData, rightOverride))
if (TryNavigate(eventData, rightOverride))
return;
break;
case MoveDirection.Down:
if(TryNavigate(eventData, downOverride))
if (TryNavigate(eventData, downOverride))
return;
break;
case MoveDirection.None:
@ -38,12 +38,13 @@ namespace NEG.UI.UnityUi.Buttons
default:
throw new ArgumentOutOfRangeException();
}
base.OnMove(eventData);
}
public static bool TryNavigate(BaseEventData eventData, OverridableNavigation overrideNavigation)
{
if(!overrideNavigation.Override)
if (!overrideNavigation.Override)
return false;
if (overrideNavigation.Selectable == null || !overrideNavigation.Selectable.IsActive())

View File

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

View File

@ -1,9 +1,7 @@
using NEG.UI.UnityUi.Window;
using NEG.UI.UnityUi.WindowSlot;
using System;
using UnityEngine;
using NEG.UI.Window;
using NEG.UI.WindowSlot;
using UnityEngine;
namespace NEG.UI.UnityUi.Buttons
{
@ -11,8 +9,9 @@ namespace NEG.UI.UnityUi.Buttons
public class OpenWindow : ButtonReaction
{
[SerializeField] private MonoWindow window;
[Header("Open on default area slot if empty")]
[SerializeField] private MonoWindowSlot slot;
[Header("Open on default area slot if empty")] [SerializeField]
private MonoWindowSlot slot;
protected override void OnClicked() => window.Open(slot);
}

View File

@ -1,13 +1,12 @@
using NEG.UI.UnityUi.Buttons.Settings;
using System;
using UnityEngine.EventSystems;
namespace NEG.UI.UnityUi.Buttons.Reaction
{
public abstract class ButtonElementBehaviour : IDisposable
{
protected SettingData baseData;
protected readonly BaseButton button;
protected SettingData baseData;
public ButtonElementBehaviour(BaseButton baseButton, SettingData settingData)
{
@ -15,8 +14,8 @@ namespace NEG.UI.UnityUi.Buttons.Reaction
baseData = settingData;
}
public virtual void ChangeData(SettingData newData) => baseData = newData;
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.Utils;
using UnityEngine;
using UnityEngine.EventSystems;
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 OnButtonDeselected(bool _) => button.Text.color = data.DeselectedColor;
}
}

View File

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

View File

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

View File

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

View File

@ -5,23 +5,11 @@ using System.Collections.Generic;
using TMPro;
using UnityEngine;
namespace NEG.UI.UnityUi
{
[PublicAPI]
public class CarouselList : MonoBehaviour
{
public event Action<int> OnSelectedItemChanged;
/// <summary>
/// Current option
/// </summary>
public string CurrentOption { get; private set; }
/// <summary>
/// Current selected option id
/// </summary>
public int CurrentOptionId { get; private set; }
[SerializeField] private BaseButton nextButton;
[SerializeField] private BaseButton prevButton;
[SerializeField] private TMP_Text currentOptionText;
@ -29,7 +17,31 @@ namespace NEG.UI.UnityUi
private List<string> options;
/// <summary>
/// Sets new options list, automatically first will be selected.
/// Current option
/// </summary>
public string CurrentOption { get; private set; }
/// <summary>
/// Current selected option id
/// </summary>
public int CurrentOptionId { get; private set; }
private void Awake()
{
nextButton.OnButtonPressed += SelectNextOption;
prevButton.OnButtonPressed += SelectPrevOption;
}
private void OnDestroy()
{
nextButton.OnButtonPressed -= SelectNextOption;
prevButton.OnButtonPressed -= SelectPrevOption;
}
public event Action<int> OnSelectedItemChanged;
/// <summary>
/// Sets new options list, automatically first will be selected.
/// </summary>
/// <param name="options">list of options names</param>
public void SetOptions(List<string> options)
@ -42,7 +54,7 @@ namespace NEG.UI.UnityUi
public void SelectPrevOption() => ChangeOption(false);
/// <summary>
/// Selects option with provided id.
/// Selects option with provided id.
/// </summary>
/// <param name="option">option number</param>
public void SelectOption(int option)
@ -52,6 +64,7 @@ namespace NEG.UI.UnityUi
Debug.LogError("Invalid option number");
return;
}
CurrentOptionId = option;
CurrentOption = options[option];
currentOptionText.text = CurrentOption;
@ -59,7 +72,7 @@ namespace NEG.UI.UnityUi
}
/// <summary>
/// Select option with provided value. Use with caution, better use <see cref="SelectOption(int)"/>.
/// Select option with provided value. Use with caution, better use <see cref="SelectOption(int)" />.
/// </summary>
/// <param name="option">option value to select</param>
public void SelectOption(string option)
@ -80,18 +93,7 @@ namespace NEG.UI.UnityUi
SelectOption(index);
}
private void Awake()
{
nextButton.OnButtonPressed += SelectNextOption;
prevButton.OnButtonPressed += SelectPrevOption;
}
private void OnDestroy()
{
nextButton.OnButtonPressed -= SelectNextOption;
prevButton.OnButtonPressed -= SelectPrevOption;
}
private void ChangeOption(bool next) => SelectOption((CurrentOptionId + (next ? 1 : -1) + options.Count) % options.Count);
private void ChangeOption(bool next) =>
SelectOption((CurrentOptionId + (next ? 1 : -1) + options.Count) % options.Count);
}
}

View File

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

View File

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

View File

@ -1,21 +1,21 @@
{
"name": "NEG.UI.UnityUi.Editor",
"rootNamespace": "",
"references": [
"GUID:e2aaf8effe1c9634d87b2edda6988a6a",
"GUID:5928dc8d9173fd348aa77d4593ca3fd8"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [
""
],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
"name": "NEG.UI.UnityUi.Editor",
"rootNamespace": "",
"references": [
"GUID:e2aaf8effe1c9634d87b2edda6988a6a",
"GUID:5928dc8d9173fd348aa77d4593ca3fd8"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [
""
],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

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

View File

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

View File

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

View File

@ -6,7 +6,6 @@ using NEG.UI.UnityUi.Popup;
using NEG.UI.UnityUi.Window;
using NEG.Utils;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.EventSystems;
@ -16,27 +15,24 @@ using Object = UnityEngine.Object;
namespace NEG.UI.UnityUi
{
/// <summary>
/// Implements ui using UnityUI and Unity Event System with New Input System.
/// <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/DefaultPopupPrefab - prefab of default popup with 2 options (has to have <see cref="MonoDefaultPopup"/> component)</para>
/// NEG_UI_DISABLE_WARNING_DEFAULT_SELECTION
/// Implements ui using UnityUI and Unity Event System with New Input System.
/// <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/DefaultPopupPrefab - prefab of default popup with 2 options (has to have
/// <see cref="MonoDefaultPopup" /> component)
/// </para>
/// NEG_UI_DISABLE_WARNING_DEFAULT_SELECTION
/// </summary>
public class MonoUiManager : UiManager, IDisposable
{
//TODO: use default unity selection
//TODO: window snaping to slots
public static new MonoUiManager Instance { get; private set; }
public ButtonSettings DefaultUiSettings { get; }
public KeyBasedFactory<string, ButtonElementBehaviour> BehavioursFactory { get; private set; }
private readonly GameObject canvasPrefab;
//TODO: editor to auto add slots, buttons
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)
{
@ -45,8 +41,10 @@ namespace NEG.UI.UnityUi
var popupCanvas = Resources.Load<GameObject>("UI/PopupCanvas");
var defaultPopup = Resources.Load<GameObject>("UI/DefaultPopupPrefab");
Assert.IsNotNull(popupCanvas,"No canvas prefab was provided. Please check MonoUiManager class documentation");
Assert.IsNotNull(defaultPopup,"No popup prefab was provided. Please check MonoUiManager class documentation");
Assert.IsNotNull(popupCanvas,
"No canvas prefab was provided. Please check MonoUiManager class documentation");
Assert.IsNotNull(defaultPopup,
"No popup prefab was provided. Please check MonoUiManager class documentation");
Assert.IsNotNull(popupCanvas.GetComponent<Canvas>());
Assert.IsNotNull(defaultPopup.GetComponent<MonoDefaultPopup>());
@ -64,6 +62,13 @@ namespace NEG.UI.UnityUi
DefaultUiSettings = defaultUiSettings;
}
//TODO: use default unity selection
//TODO: window snaping to slots
public static new MonoUiManager Instance { get; private set; }
public ButtonSettings DefaultUiSettings { get; }
public KeyBasedFactory<string, ButtonElementBehaviour> BehavioursFactory { get; }
public override void Dispose()
{
base.Dispose();
@ -73,12 +78,13 @@ namespace NEG.UI.UnityUi
protected override void UpdatePopupsState(bool forceShow, int priority = 0, PopupData data = null)
{
base.UpdatePopupsState(forceShow, priority, data);
if(inputModule.CurrentSelectionSource != SelectionSource.Direction)
if (inputModule.CurrentSelectionSource != SelectionSource.Direction)
return;
if (CurrentPopup == null && (EventSystem.current.currentSelectedGameObject == null || !EventSystem.current.currentSelectedGameObject.activeInHierarchy))
if (CurrentPopup == null && (EventSystem.current.currentSelectedGameObject == null ||
!EventSystem.current.currentSelectedGameObject.activeInHierarchy))
{
if(((MonoWindow)CurrentMainWindow).DefaultSelectedItem == null)
if (((MonoWindow)CurrentMainWindow).DefaultSelectedItem == null)
return;
EventSystem.current.SetSelectedGameObject(((MonoWindow)CurrentMainWindow).DefaultSelectedItem);
}

View File

@ -1,25 +1,25 @@
{
"name": "NEG.UI.UnityUi",
"rootNamespace": "",
"references": [
"GUID:343deaaf83e0cee4ca978e7df0b80d21",
"GUID:7361f1d9c43da6649923760766194746",
"GUID:6055be8ebefd69e48b49212b09b47b2f",
"GUID:23eed6c2401dca1419d1ebd180e58c5a",
"GUID:33759803a11f4d538227861a78aba30b",
"GUID:0c752da273b17c547ae705acf0f2adf2",
"GUID:3c4294719a93e3c4e831a9ff0c261e8a",
"GUID:75469ad4d38634e559750d17036d5f7c"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [
""
],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
"name": "NEG.UI.UnityUi",
"rootNamespace": "",
"references": [
"GUID:343deaaf83e0cee4ca978e7df0b80d21",
"GUID:7361f1d9c43da6649923760766194746",
"GUID:6055be8ebefd69e48b49212b09b47b2f",
"GUID:23eed6c2401dca1419d1ebd180e58c5a",
"GUID:33759803a11f4d538227861a78aba30b",
"GUID:0c752da273b17c547ae705acf0f2adf2",
"GUID:3c4294719a93e3c4e831a9ff0c261e8a",
"GUID:75469ad4d38634e559750d17036d5f7c"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [
""
],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

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

View File

@ -6,9 +6,8 @@ namespace NEG.UI.UnityUi.Popup
{
public class MonoPopup : MonoBehaviour, IPopup
{
public event Action<PopupData> OnPopupClosed;
protected PopupData data;
public event Action<PopupData> OnPopupClosed;
public virtual void Show(PopupData data)
{
@ -20,11 +19,10 @@ namespace NEG.UI.UnityUi.Popup
{
gameObject.SetActive(false);
if(silent)
if (silent)
return;
OnPopupClosed?.Invoke(data);
}
}
}

View File

@ -7,7 +7,7 @@ namespace NEG.UI.UnityUi.Window
{
public class CloseWindowOnBack : MonoController
{
[SerializeField, Self(Flag.Editable)] private MonoWindow window;
[SerializeField] [Self(Flag.Editable)] private MonoWindow window;
protected override void OnBackUsed(IControllable.BackUsed backUsed)
{

View File

@ -1,6 +1,4 @@
using NEG.UI.Area;
using NEG.UI.UnityUi.Buttons;
using NEG.UI.UnityUi.WindowSlot;
using NEG.UI.UnityUi.WindowSlot;
using NEG.UI.Window;
using NEG.UI.WindowSlot;
using NegUtils.NEG.UI;
@ -8,30 +6,44 @@ using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;
namespace NEG.UI.UnityUi.Window
{
[DefaultExecutionOrder(10)]
public class MonoWindow : MonoBehaviour, IWindow
{
public event Action<object> OnOpened;
public event Action OnClosed;
public event Action<IControllable.BackUsed> OnBackUsed;
[SerializeField] private List<MonoWindowSlot> windowSlots;
public IEnumerable<IWindowSlot> AvailableSlots => windowSlots;
public IWindowSlot Parent { get; private set; }
[SerializeField] private GameObject defaultSelectedItem;
public bool IsMainWindow { get; private set; }
public bool IsMainWindow { get; }
public bool IsOpened { get; protected set; }
private IWindowSlot DefaultWindowSlot => windowSlots[0];
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)
{
@ -58,28 +70,10 @@ namespace NEG.UI.UnityUi.Window
public void SeVisibleState() => gameObject.SetActive(true);
private void Awake() => ((IWindow)this).SetHiddenState();
private void OnDestroy()
{
if (IsOpened)
{
UiManager.Instance.OnWindowClosed(this);
}
}
private void OnValidate()
{
#if !NEG_UI_DISABLE_WARNING_DEFAULT_SELECTION
if(defaultSelectedItem == null)
Debug.LogWarning($"Window {name} should have default selected item set");
#endif
}
public void OpenWindow(IWindow window, object data = null) => DefaultWindowSlot.AttachWindow(window, data);
public void SetDefaultSelectedItem(GameObject item) => defaultSelectedItem = item;
public void TryUseBack(ref IControllable.BackUsed backUsed) => OnBackUsed?.Invoke(backUsed);
public void SetDefaultSelectedItem(GameObject item) => defaultSelectedItem = item;
}
}

View File

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

View File

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

View File

@ -3,13 +3,16 @@ using NEG.UI.UnityUi.Window;
using NEG.UI.UnityUi.WindowSlot;
using NEG.UI.Window;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.EventSystems;
namespace NegUtils.NEG.UI.UnityUi.WindowSlot
{
public class SingleWindowSlotWithHistory : MonoWindowSlot
{
private readonly List<IWindow> windowsHistory = new();
private IWindow currentWindow;
public IWindow 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)
{
CurrentWindow = window;
@ -39,24 +38,22 @@ namespace NegUtils.NEG.UI.UnityUi.WindowSlot
public override void DetachWindow(IWindow window)
{
if(window == null)
if (window == null)
return;
window.SetClosedState();
windowsHistory.Remove(window);
if (window != currentWindow || windowsHistory.Count == 0) return;
currentWindow = windowsHistory[^1];
currentWindow.SeVisibleState();
if(UiManager.Instance.CurrentMainWindow == window)
if (UiManager.Instance.CurrentMainWindow == window)
UiManager.Instance.MainWindowClosed(window);
EventSystem.current.SetSelectedGameObject(((MonoWindow)currentWindow).DefaultSelectedItem);
}
public override void CloseAllWindows()
{
currentWindow = null;
foreach (var window in windowsHistory)
{
window.SetClosedState();
}
foreach (var window in windowsHistory) window.SetClosedState();
windowsHistory.Clear();
}
}

View File

@ -1,5 +1,4 @@
using JetBrains.Annotations;
using NEG.UI.Area;
using NEG.UI.Area;
using NEG.UI.WindowSlot;
using NegUtils.NEG.UI;
using UnityEngine;
@ -9,29 +8,29 @@ namespace NEG.UI.Window
public interface IWindow : ISlotsHolder, IControllable
{
/// <summary>
/// Parent slot of this window.
/// Parent slot of this window.
/// </summary>
IWindowSlot Parent { get; }
/// <summary>
/// Called internally by slot to open window.
/// Called internally by slot to open window.
/// </summary>
/// <param name="parentSlot">slot that opens window</param>
/// <param name="data">data</param>
void SetOpenedState(IWindowSlot parentSlot, object data);
/// <summary>
/// Called internally to close window by slot.
/// Called internally to close window by slot.
/// </summary>
void SetClosedState();
/// <summary>
/// Called internally to hide window by slot.
/// Called internally to hide window by slot.
/// </summary>
void SetHiddenState();
/// <summary>
/// Called internally to set window visible by slot.
/// Called internally to set window visible by slot.
/// </summary>
void SeVisibleState();
}
@ -39,7 +38,7 @@ namespace NEG.UI.Window
public static class WindowInterfaceExtensions
{
/// <summary>
/// Opens window as slot child. If slot is null or not provided, as child of current area.
/// Opens window as slot child. If slot is null or not provided, as child of current area.
/// </summary>
/// <param name="window">window to open</param>
/// <param name="slot">slot to attach window</param>
@ -56,7 +55,7 @@ namespace NEG.UI.Window
}
/// <summary>
/// Opens window as child of selected area.
/// Opens window as child of selected area.
/// </summary>
/// <param name="window">window to open</param>
/// <param name="area">area to attach window</param>
@ -64,7 +63,7 @@ namespace NEG.UI.Window
public static void Open(this IWindow window, IArea area, object data = null) => area.OpenWindow(window, data);
/// <summary>
/// Open passed window as child of this window.
/// Open passed window as child of this window.
/// </summary>
/// <param name="window">parent window</param>
/// <param name="windowToOpen">window to open</param>
@ -73,14 +72,16 @@ namespace NEG.UI.Window
{
if (windowToOpen == null)
{
Debug.LogError($"Window to open cannot be null");
Debug.LogError("Window to open cannot be null");
return;
}
window.OpenWindow(windowToOpen, data);
}
/// <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>
/// <param name="window">window to open</param>
/// <param name="parentWindow">parent window</param>
@ -103,7 +104,7 @@ namespace NEG.UI.Window
}
/// <summary>
/// Close window.
/// Close window.
/// </summary>
/// <param name="window">window to close</param>
public static void Close(this IWindow window) => window.Parent.DetachWindow(window);

View File

@ -8,7 +8,7 @@ namespace NEG.UI.WindowSlot
IEnumerable<IWindowSlot> AvailableSlots { get; }
/// <summary>
/// Open window
/// Open window
/// </summary>
/// <param name="window"></param>
/// <param name="data"></param>
@ -16,10 +16,7 @@ namespace NEG.UI.WindowSlot
void CloseAllWindows()
{
foreach (var slot in AvailableSlots)
{
slot.CloseAllWindows();
}
foreach (var slot in AvailableSlots) slot.CloseAllWindows();
}
}
}

View File

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

View File

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

View File

@ -5,12 +5,6 @@ namespace NEG.Utils.Timing
{
public class AutoTimeMachine
{
[PublicAPI]
public double Interval { get; set; }
[PublicAPI]
public Action Action { get; }
private readonly TimeMachine machine;
public AutoTimeMachine(Action action, double interval)
@ -20,18 +14,19 @@ namespace NEG.Utils.Timing
machine = new TimeMachine();
}
[PublicAPI] public double Interval { get; set; }
[PublicAPI] public Action Action { get; }
/// <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>
/// <param name="time">Amount of time to forward by</param>
public void Forward(double time)
{
machine.Accumulate(time);
int rolls = machine.RetrieveAll(Interval);
for (int i = 0; i < rolls; i++)
{
Action();
}
for (int i = 0; i < rolls; i++) Action();
}
}
}

View File

@ -13,32 +13,34 @@ namespace NEG.Utils.Timing
}
/// <summary>
/// Adds time into the TimeMachine
/// Adds time into the TimeMachine
/// </summary>
/// <param name="time">Amount of time to be added</param>
public void Accumulate(double time) => timeInternal += time;
/// <summary>
/// Retrieves given amount of time from the TimeMachine
/// Retrieves given amount of time from the TimeMachine
/// </summary>
/// <param name="maxTime"></param>
/// <returns>Amount of time retrieved</returns>
public double Retrieve(double maxTime)
{
if(!double.IsFinite(maxTime))
if (!double.IsFinite(maxTime))
{
double timeRetrieved = timeInternal;
timeInternal = 0;
return timeRetrieved;
}
double timeLeft = timeInternal - maxTime;
timeInternal = Math.Max(timeLeft, 0);
return Math.Min(maxTime + timeLeft, maxTime);
}
/// <summary>
/// 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
/// 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
/// </summary>
/// <param name="time"></param>
public bool TryRetrieve(double time)
@ -50,7 +52,8 @@ namespace NEG.Utils.Timing
}
/// <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>
/// <param name="interval">Single unit of warp time, 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
{

View File

@ -4,12 +4,10 @@ namespace NEG.Utils.UiToolkits
{
public class MultiSelectChipItem
{
public VisualElement VisualElement { get; }
public IMultiSelectChipItem ChipItem { get; }
private readonly MultiSelectChips parent;
public MultiSelectChipItem(VisualElement visualElement, IMultiSelectChipItem element, MultiSelectChips multiSelectChips)
public MultiSelectChipItem(VisualElement visualElement, IMultiSelectChipItem element,
MultiSelectChips multiSelectChips)
{
VisualElement = visualElement;
ChipItem = element;
@ -18,5 +16,8 @@ namespace NEG.Utils.UiToolkits
visualElement.Q<VisualElement>("Color").style.backgroundColor = element.Color;
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.UIElements;
using System.Collections.Generic;
using System;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
#endif
@ -11,8 +10,30 @@ namespace NEG.Utils.UiToolkits
{
public class MultiSelectChips : VisualElement
{
public event Action<IMultiSelectChipItem> OnTryingToRemoveItem;
public event Action<Rect> OnTryingToAddItem;
private readonly List<MultiSelectChipItem> spawnedItems = new();
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
{
@ -21,10 +42,7 @@ namespace NEG.Utils.UiToolkits
{
if (!string.IsNullOrEmpty(value))
{
if (label == null)
{
InitLabel();
}
if (label == null) InitLabel();
label.text = value;
}
@ -47,53 +65,8 @@ namespace NEG.Utils.UiToolkits
}
}
private Label label;
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 event Action<IMultiSelectChipItem> OnTryingToRemoveItem;
public event Action<Rect> OnTryingToAddItem;
public void UpdateItems()
{
@ -102,7 +75,7 @@ namespace NEG.Utils.UiToolkits
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)
{
@ -113,10 +86,8 @@ namespace NEG.Utils.UiToolkits
List<IMultiSelectChipItem> itemsToAdd = new(itemsSource);
foreach (var item in spawnedItems)
{
if (itemsToAdd.Contains(item.ChipItem))
itemsToAdd.Remove(item.ChipItem);
}
foreach (var item in itemsToAdd)
{
@ -130,10 +101,7 @@ namespace NEG.Utils.UiToolkits
private void InitLabel()
{
label = new Label()
{
pickingMode = PickingMode.Ignore
};
label = new Label { pickingMode = PickingMode.Ignore };
Insert(0, label);
}
@ -148,5 +116,25 @@ namespace NEG.Utils.UiToolkits
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: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: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 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:VisualElement>
</ui:UXML>

View File

@ -1,5 +1,7 @@
<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:Button text="+" display-tooltip-when-elided="true" name="AddItem" />
<ui:Button text="+" display-tooltip-when-elided="true" name="AddItem"/>
</ui:VisualElement>
</ui:UXML>

View File

@ -1,28 +1,28 @@
{
"name": "NEG_UiToolkit",
"rootNamespace": "",
"references": [
"Unity.Addressables",
"Unity.ResourceManager"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [
{
"name": "com.unity.addressables",
"expression": "",
"define": "ADDRESSABLES"
},
{
"name": "com.unity.modules.uielements",
"expression": "",
"define": "UI_ELEMENTS"
}
],
"noEngineReferences": false
"name": "NEG_UiToolkit",
"rootNamespace": "",
"references": [
"Unity.Addressables",
"Unity.ResourceManager"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [
{
"name": "com.unity.addressables",
"expression": "",
"define": "ADDRESSABLES"
},
{
"name": "com.unity.modules.uielements",
"expression": "",
"define": "UI_ELEMENTS"
}
],
"noEngineReferences": false
}

View File

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