AlicizaX/Client/Assets/InputGlyph/InputGlyphDatabase.cs
2025-12-17 20:03:29 +08:00

106 lines
3.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.U2D;
namespace AlicizaX.InputGlyph
{
[Serializable]
public class GlyphEntry
{
public Sprite Sprite;
public InputAction action;
}
[Serializable]
public class DeviceGlyphTable
{
// Table 名称(序列化)
public string deviceName;
// 支持三种来源:
// 1) TMP Sprite AssetTextMeshPro sprite asset
public TMP_SpriteAsset tmpAsset;
// 2) Unity SpriteAtlas可选
public SpriteAtlas spriteAtlas;
// 3) Texture2DSprite Mode = Multiple在 Sprite Editor 切好的切片
public Texture2D spriteSheetTexture;
public List<GlyphEntry> entries = new List<GlyphEntry>();
}
[CreateAssetMenu(fileName = "InputGlyphDatabase", menuName = "InputGlyphs/InputGlyphDatabase", order = 400)]
public class InputGlyphDatabase : ScriptableObject
{
public List<DeviceGlyphTable> tables = new List<DeviceGlyphTable>();
// 当 FindEntryByControlPath 传空 path 时返回的占位 sprite
public Sprite placeholderSprite;
public DeviceGlyphTable GetTable(string deviceName)
{
if (string.IsNullOrEmpty(deviceName)) return null;
if (tables == null) return null;
for (int i = 0; i < tables.Count; ++i)
{
var t = tables[i];
if (t == null) continue;
if (string.Equals(t.deviceName, deviceName, StringComparison.OrdinalIgnoreCase))
return t;
}
return null;
}
// 兼容枚举版本(示例)
public DeviceGlyphTable GetTable(InputDeviceWatcher.InputDeviceCategory device)
{
string name = "Other";
switch (device)
{
case InputDeviceWatcher.InputDeviceCategory.Keyboard: name = "Keyboard"; break;
case InputDeviceWatcher.InputDeviceCategory.Xbox: name = "Xbox"; break;
case InputDeviceWatcher.InputDeviceCategory.PlayStation: name = "PlayStation"; break;
default: name = "Xbox"; break;
}
return GetTable(name);
}
public Sprite FindSprite(string controlPath, InputDeviceWatcher.InputDeviceCategory device)
{
var entry = FindEntryByControlPath(controlPath, device);
if (string.IsNullOrEmpty(controlPath) || entry == null)
{
return placeholderSprite;
}
return entry.Sprite;
}
public GlyphEntry FindEntryByControlPath(string controlPath, InputDeviceWatcher.InputDeviceCategory device)
{
var t = GetTable(device);
if (t != null)
{
for (int i = 0; i < t.entries.Count; ++i)
{
var e = t.entries[i];
if (e == null) continue;
if (e.action == null) continue;
if (e.action.bindings.Count <= 0) continue;
foreach (var binding in e.action.bindings)
{
if (string.Equals(controlPath, binding.path, StringComparison.OrdinalIgnoreCase))
{
return e;
}
}
}
}
return null;
}
}
}