添加询问李诫(AI 问答)功能

- 添加 AIChatComponent:用于主要的逻辑(构造请求,解析响应)
- 添加 AIChatForm:用于问答的页面展示
This commit is contained in:
SepComet
2026-02-25 17:25:09 +08:00
parent b00ea1a14f
commit f8c0f46c36
70 changed files with 7059 additions and 607 deletions
+16 -10
View File
@@ -11,17 +11,20 @@ using UnityEngine.EventSystems;
namespace UI
{
public class CommonButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler, IPointerUpHandler
public class CommonButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler,
IPointerUpHandler
{
private const float FadeTime = 0.3f;
private const float OnHoverAlpha = 0.7f;
private const float OnClickAlpha = 0.6f;
[SerializeField]
private UnityEvent m_OnHover = null;
[SerializeField] private bool _allowFade = true;
[SerializeField]
private UnityEvent m_OnClick = null;
[SerializeField] private UnityEvent m_OnHover = null;
[SerializeField] private UnityEvent m_OnClick = null;
[SerializeField] private UnityEvent m_OnHoverEnd = null;
private CanvasGroup m_CanvasGroup = null;
@@ -43,8 +46,9 @@ namespace UI
}
StopAllCoroutines();
StartCoroutine(m_CanvasGroup.FadeToAlpha(OnHoverAlpha, FadeTime));
m_OnHover.Invoke();
if (_allowFade)
StartCoroutine(m_CanvasGroup.FadeToAlpha(OnHoverAlpha, FadeTime));
m_OnHover?.Invoke();
}
public void OnPointerExit(PointerEventData eventData)
@@ -55,7 +59,9 @@ namespace UI
}
StopAllCoroutines();
StartCoroutine(m_CanvasGroup.FadeToAlpha(1f, FadeTime));
if (_allowFade)
StartCoroutine(m_CanvasGroup.FadeToAlpha(1f, FadeTime));
m_OnHoverEnd?.Invoke();
}
public void OnPointerDown(PointerEventData eventData)
@@ -66,7 +72,7 @@ namespace UI
}
m_CanvasGroup.alpha = OnClickAlpha;
m_OnClick.Invoke();
m_OnClick?.Invoke();
}
public void OnPointerUp(PointerEventData eventData)
@@ -79,4 +85,4 @@ namespace UI
m_CanvasGroup.alpha = OnHoverAlpha;
}
}
}
}
@@ -0,0 +1,13 @@
using System.Collections.Generic;
namespace UI
{
public class AIChatFormContext : UIContext
{
public AIChatFormController Controller;
public string Title = "AI Chat";
public bool ClearHistoryOnOpen = true;
public int LanguageMode = 0;
public List<AIChatMessageContext> Messages = new List<AIChatMessageContext>();
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: bd7b7032876cfea4fba511fe86a86ca4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
namespace UI
{
public sealed class AIChatMessageContext : UIContext
{
public bool IsPlayer;
public string Content;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0b757f1a76817344396df2fbc235f7a6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
namespace UI
{
public class AIDialogItemContext : UIContext
{
public float ParentWidth;
public string Content;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2740182b0799e4b4288755e07fd7244b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,7 @@
namespace UI
{
public class PlayerDialogItemContext : UIContext
{
public string Content;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 10f44b172e664044fa1747d2e45f8c4f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,376 @@
using System.Collections.Generic;
using System.Text;
using CustomComponent;
using GameFramework.Event;
using UnityGameFramework.Runtime;
namespace UI
{
public class AIChatFormController : IFormController<AIChatFormContext>
{
private AIChatFormContext _context;
private AIChatForm _aiChatForm;
private int? _formSerialId;
private bool _pendingRefresh;
private bool _aiChatEventsBound;
private bool _isStreaming;
private int _streamingMessageIndex = -1;
private readonly StringBuilder _streamingMessageBuffer = new StringBuilder();
public AIChatFormController()
{
GameEntry.Event.Subscribe(OpenUIFormSuccessEventArgs.EventId, OnOpenUIFormSuccess);
GameEntry.Event.Subscribe(CloseUIFormCompleteEventArgs.EventId, OnCloseUIFormComplete);
}
public int? OpenUI(AIChatFormContext context)
{
if (context == null)
{
Log.Warning("AIChatFormController open failed. context is null.");
return null;
}
EnsureAIChatEventBinding();
context.Controller = this;
context.Messages ??= new List<AIChatMessageContext>();
_context = context;
if (_aiChatForm != null)
{
_aiChatForm.RefreshUI(_context);
return _formSerialId;
}
CloseUI();
_pendingRefresh = true;
_formSerialId = GameEntry.UI.OpenUIForm(UIFormId.AIChatForm, context);
return _formSerialId;
}
public void CloseUI()
{
_pendingRefresh = false;
if (_formSerialId.HasValue)
{
GameEntry.UI.CloseUIForm(_formSerialId.Value);
return;
}
if (_aiChatForm != null)
{
_aiChatForm.Close();
}
}
public void SubmitPlayerMessage(string input, int languageMode)
{
string trimmedInput = input == null ? string.Empty : input.Trim();
if (string.IsNullOrEmpty(trimmedInput))
{
return;
}
if (_isStreaming)
{
PublishErrorMessage("AI is still responding. Please wait.");
return;
}
EnsureAIChatEventBinding();
if (_context == null)
{
_context = new AIChatFormContext
{
Controller = this,
LanguageMode = 0,
Messages = new List<AIChatMessageContext>()
};
}
_context.LanguageMode = languageMode;
AddMessageToContext(true, trimmedInput);
_aiChatForm?.AppendPlayerDialog(new PlayerDialogItemContext
{
Content = trimmedInput
});
AIChatComponent aiChat = GameEntry.AIChat;
if (aiChat == null)
{
PublishErrorMessage("AIChatComponent is missing.");
return;
}
bool sendStarted = aiChat.SendChat(trimmedInput, BuildLanguageInstruction(languageMode));
if (!sendStarted)
{
PublishErrorMessage(string.IsNullOrEmpty(aiChat.LastRequestErrorMessage)
? "Failed to start AI chat request."
: aiChat.LastRequestErrorMessage);
return;
}
_isStreaming = true;
_streamingMessageIndex = -1;
_streamingMessageBuffer.Length = 0;
_aiChatForm?.SetInputInteractable(false);
}
private static string BuildLanguageInstruction(int languageMode)
{
if (languageMode == 1)
{
return "\u8bf7\u4f7f\u7528\u6587\u8a00\u6587\u56de\u7b54\uff0c\u8bed\u8a00\u5c3d\u91cf\u7b80\u6d01\u3001\u96c5\u6b63\u3001\u901a\u987a\u3002";
}
return "\u8bf7\u4f7f\u7528\u73b0\u4ee3\u767d\u8bdd\u6587\u56de\u7b54\uff0c\u8bed\u8a00\u6e05\u6670\u81ea\u7136\u3001\u6613\u4e8e\u7406\u89e3\u3002";
}
~AIChatFormController()
{
GameEntry.Event.Unsubscribe(OpenUIFormSuccessEventArgs.EventId, OnOpenUIFormSuccess);
GameEntry.Event.Unsubscribe(CloseUIFormCompleteEventArgs.EventId, OnCloseUIFormComplete);
UnbindAIChatEvents();
}
private void EnsureAIChatEventBinding()
{
if (_aiChatEventsBound)
{
return;
}
AIChatComponent aiChat = GameEntry.AIChat;
if (aiChat == null)
{
return;
}
aiChat.StreamTextUpdated += OnStreamTextUpdated;
aiChat.StreamRequestCompleted += OnStreamRequestCompleted;
aiChat.StreamRequestFailed += OnStreamRequestFailed;
_aiChatEventsBound = true;
}
private void UnbindAIChatEvents()
{
if (!_aiChatEventsBound)
{
return;
}
AIChatComponent aiChat = GameEntry.AIChat;
if (aiChat == null)
{
_aiChatEventsBound = false;
return;
}
aiChat.StreamTextUpdated -= OnStreamTextUpdated;
aiChat.StreamRequestCompleted -= OnStreamRequestCompleted;
aiChat.StreamRequestFailed -= OnStreamRequestFailed;
_aiChatEventsBound = false;
}
private void TryRefreshUI()
{
if (_context == null)
{
return;
}
if (_aiChatForm == null)
{
_pendingRefresh = true;
return;
}
_aiChatForm.RefreshUI(_context);
_pendingRefresh = false;
}
private void AddMessageToContext(bool isPlayer, string content)
{
if (_context == null)
{
return;
}
_context.Messages ??= new List<AIChatMessageContext>();
_context.Messages.Add(new AIChatMessageContext
{
IsPlayer = isPlayer,
Content = content
});
}
private void PublishErrorMessage(string errorMessage)
{
string content = string.IsNullOrEmpty(errorMessage) ? "Unknown error." : errorMessage;
string formattedContent = "[Error] " + content;
AddMessageToContext(false, formattedContent);
_aiChatForm?.AppendAIDialog(new AIDialogItemContext
{
ParentWidth = GetContentWidth(),
Content = formattedContent
});
_aiChatForm?.SetInputInteractable(true);
_isStreaming = false;
_streamingMessageIndex = -1;
_streamingMessageBuffer.Length = 0;
}
private void EndStreaming(string finalAIContent)
{
string content = string.IsNullOrEmpty(finalAIContent) ? string.Empty : finalAIContent;
if (_streamingMessageIndex >= 0)
{
_aiChatForm?.UpdateAIDialog(_streamingMessageIndex, new AIDialogItemContext
{
ParentWidth = GetContentWidth(),
Content = content
});
}
else if (!string.IsNullOrEmpty(content))
{
_aiChatForm?.AppendAIDialog(new AIDialogItemContext
{
ParentWidth = GetContentWidth(),
Content = content
});
}
if (!string.IsNullOrEmpty(content))
{
AddMessageToContext(false, content);
}
_isStreaming = false;
_streamingMessageIndex = -1;
_streamingMessageBuffer.Length = 0;
_aiChatForm?.SetInputInteractable(true);
_aiChatForm?.FocusInputField();
}
private void OnStreamTextUpdated(string delta)
{
if (!_isStreaming)
{
return;
}
if (string.IsNullOrEmpty(delta))
{
return;
}
_streamingMessageBuffer.Append(delta);
if (_streamingMessageIndex < 0 && _aiChatForm != null)
{
_streamingMessageIndex = _aiChatForm.AppendAIDialog(new AIDialogItemContext
{
ParentWidth = GetContentWidth(),
Content = string.Empty
});
}
if (_streamingMessageIndex >= 0)
{
_aiChatForm?.UpdateAIDialog(_streamingMessageIndex, new AIDialogItemContext
{
ParentWidth = GetContentWidth(),
Content = _streamingMessageBuffer.ToString()
});
}
}
private float GetContentWidth()
{
return _aiChatForm != null ? _aiChatForm.ContentSize.x : 0f;
}
private void OnStreamRequestCompleted(string response)
{
if (!_isStreaming)
{
return;
}
string finalText = string.IsNullOrEmpty(response) ? _streamingMessageBuffer.ToString() : response;
EndStreaming(finalText);
}
private void OnStreamRequestFailed(string errorMessage)
{
if (!_isStreaming)
{
PublishErrorMessage(errorMessage);
return;
}
string partialContent = _streamingMessageBuffer.ToString();
if (string.IsNullOrEmpty(partialContent))
{
EndStreaming("[Error] " + (string.IsNullOrEmpty(errorMessage) ? "Request failed." : errorMessage));
return;
}
EndStreaming(partialContent + "\n\n[Error] " +
(string.IsNullOrEmpty(errorMessage) ? "Request failed." : errorMessage));
}
private void OnOpenUIFormSuccess(object sender, GameEventArgs e)
{
if (!(e is OpenUIFormSuccessEventArgs args))
{
return;
}
if (!_formSerialId.HasValue)
{
return;
}
if (args.UIForm == null || args.UIForm.SerialId != _formSerialId.Value || args.UserData != _context)
{
return;
}
_aiChatForm = args.UIForm.Logic as AIChatForm;
if (_aiChatForm == null)
{
Log.Warning("AIChatFormController open success but form logic is invalid.");
return;
}
if (_pendingRefresh)
{
TryRefreshUI();
}
}
private void OnCloseUIFormComplete(object sender, GameEventArgs e)
{
if (!(e is CloseUIFormCompleteEventArgs args))
{
return;
}
if (args.SerialId != _formSerialId)
{
return;
}
_aiChatForm = null;
_formSerialId = null;
_pendingRefresh = false;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7b81d9526357e63489249ce90808e71c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,333 @@
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using UnityGameFramework.Runtime;
namespace UI
{
public class AIChatForm : UGuiForm
{
[SerializeField] private TMP_Text _returnButtonText;
[SerializeField] private TMP_InputField _inputField;
[SerializeField] private RectTransform _dialogContent;
[SerializeField] private TMP_Text _titleText;
[SerializeField] private ScrollRect _historyScrollRect;
[SerializeField] private AIDialogItem _aiDialogItemPrefab;
[SerializeField] private PlayerDialogItem _playerDialogItemPrefab;
[SerializeField] private HorizonSelectGroup _languageSelectGroup;
[SerializeField] private string _returnButtonNormalText = "<sprite name=\"KEYBOARD_Esc\"> Back";
[SerializeField] private string _returnButtonHoverText = "<sprite name=\"KEYBOARD_Esc\"><u> Back </u>";
private readonly List<Component> _dialogItems = new List<Component>();
private AIChatFormController _controller;
private VerticalLayoutGroup _contentLayoutGroup;
public Vector2 ContentSize => _dialogContent != null
? new Vector2(_dialogContent.rect.width, _dialogContent.rect.height)
: Vector2.zero;
protected override void OnOpen(object userData)
{
base.OnOpen(userData);
EnsureReferences();
if (_inputField != null)
{
_inputField.onSubmit.RemoveListener(OnInputFieldSubmitted);
_inputField.onSubmit.AddListener(OnInputFieldSubmitted);
}
if (!(userData is AIChatFormContext context))
{
Log.Error("AIChatFormContext is invalid.");
return;
}
RefreshUI(context);
}
protected override void OnClose(bool isShutdown, object userData)
{
if (_inputField != null)
{
_inputField.onSubmit.RemoveListener(OnInputFieldSubmitted);
}
ClearDialogItems();
_dialogItems.Clear();
_controller = null;
base.OnClose(isShutdown, userData);
}
public void RefreshUI(AIChatFormContext context)
{
EnsureReferences();
if (context == null)
{
return;
}
_controller = context.Controller;
if (_titleText != null && !string.IsNullOrEmpty(context.Title))
{
_titleText.text = context.Title;
}
if (_languageSelectGroup != null)
{
int targetLanguageMode = Mathf.Max(0, context.LanguageMode);
try
{
_languageSelectGroup.SetValue(targetLanguageMode);
}
catch
{
_languageSelectGroup.SetValue(0);
context.LanguageMode = 0;
}
}
if (context.ClearHistoryOnOpen || _dialogItems.Count == 0)
{
ClearDialogItems();
BuildHistory(context.Messages);
}
FocusInputField();
}
public int AppendAIDialog(AIDialogItemContext context)
{
EnsureReferences();
if (_aiDialogItemPrefab == null || _dialogContent == null)
{
Log.Warning("Append AI dialog failed. Missing AI item prefab or content root.");
return -1;
}
AIDialogItem item = Instantiate(_aiDialogItemPrefab, _dialogContent, false);
item.gameObject.SetActive(true);
item.OnInit(context);
_dialogItems.Add(item);
ScrollToBottom();
return _dialogItems.Count - 1;
}
public void UpdateAIDialog(int itemIndex, AIDialogItemContext context)
{
if (itemIndex < 0 || itemIndex >= _dialogItems.Count)
{
return;
}
if (!(_dialogItems[itemIndex] is AIDialogItem item))
{
return;
}
item.OnInit(context);
ScrollToBottom();
}
public int AppendPlayerDialog(PlayerDialogItemContext context)
{
EnsureReferences();
if (_playerDialogItemPrefab == null || _dialogContent == null)
{
Log.Warning("Append player dialog failed. Missing player item prefab or content root.");
return -1;
}
PlayerDialogItem item = Instantiate(_playerDialogItemPrefab, _dialogContent, false);
item.gameObject.SetActive(true);
item.OnInit(context);
_dialogItems.Add(item);
ScrollToBottom();
return _dialogItems.Count - 1;
}
public void SetInputInteractable(bool interactable)
{
if (_inputField == null)
{
return;
}
_inputField.interactable = interactable;
}
public void FocusInputField()
{
if (_inputField == null || !_inputField.interactable)
{
return;
}
_inputField.Select();
_inputField.ActivateInputField();
}
public void OnCommitButtonClick()
{
CommitInput();
}
public void OnReturnButtonHover()
{
if (_returnButtonText != null)
{
_returnButtonText.text = _returnButtonHoverText;
}
}
public void OnReturnButtonClick()
{
_controller?.CloseUI();
}
public void OnReturnButtonHoverEnd()
{
if (_returnButtonText != null)
{
_returnButtonText.text = _returnButtonNormalText;
}
}
private void EnsureReferences()
{
if (_historyScrollRect == null)
{
_historyScrollRect = GetComponentInChildren<ScrollRect>(true);
}
if (_historyScrollRect != null && _dialogContent == null)
{
_dialogContent = _historyScrollRect.content;
}
if (_dialogContent != null)
{
_contentLayoutGroup = _dialogContent.GetComponent<VerticalLayoutGroup>();
if (_contentLayoutGroup == null)
{
_contentLayoutGroup = _dialogContent.gameObject.AddComponent<VerticalLayoutGroup>();
}
_contentLayoutGroup.enabled = true;
_contentLayoutGroup.childAlignment = TextAnchor.UpperLeft;
_contentLayoutGroup.childForceExpandHeight = false;
_contentLayoutGroup.childForceExpandWidth = true;
_contentLayoutGroup.childControlHeight = true;
_contentLayoutGroup.childControlWidth = true;
_contentLayoutGroup.spacing = 12f;
}
}
private void BuildHistory(List<AIChatMessageContext> messages)
{
if (messages == null || messages.Count == 0)
{
return;
}
for (int i = 0; i < messages.Count; i++)
{
AIChatMessageContext message = messages[i];
if (message == null || string.IsNullOrEmpty(message.Content))
{
continue;
}
if (message.IsPlayer)
{
AppendPlayerDialog(new PlayerDialogItemContext
{
Content = message.Content
});
}
else
{
AppendAIDialog(new AIDialogItemContext
{
ParentWidth = ContentSize.x,
Content = message.Content
});
}
}
}
private void CommitInput()
{
if (_controller == null || _inputField == null || !_inputField.interactable)
{
return;
}
string content = _inputField.text;
_inputField.text = string.Empty;
_controller.SubmitPlayerMessage(content, GetLanguageMode());
FocusInputField();
}
private void OnInputFieldSubmitted(string submittedText)
{
CommitInput();
}
private int GetLanguageMode()
{
return _languageSelectGroup != null ? _languageSelectGroup.GetIntValue() : 0;
}
private void ClearDialogItems()
{
if (_dialogContent == null)
{
_dialogItems.Clear();
return;
}
for (int i = _dialogContent.childCount - 1; i >= 0; i--)
{
Transform child = _dialogContent.GetChild(i);
if (child != null)
{
Destroy(child.gameObject);
}
}
_dialogItems.Clear();
}
private void ScrollToBottom()
{
if (_historyScrollRect == null)
{
return;
}
StopCoroutine(nameof(ScrollToBottomAtEndOfFrame));
StartCoroutine(nameof(ScrollToBottomAtEndOfFrame));
}
private IEnumerator ScrollToBottomAtEndOfFrame()
{
yield return null;
Canvas.ForceUpdateCanvases();
_historyScrollRect.verticalNormalizedPosition = 0f;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e59af4c8fe70e184ea5ab8d33fe39c4b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,90 @@
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace UI
{
public class AIDialogItem : MonoBehaviour
{
[SerializeField] private RectTransform _rectTransform;
[SerializeField] private TMP_Text _contentText;
private LayoutElement _layoutElement;
private float _minHeight;
private void Awake()
{
CacheReferences();
}
public void OnInit(AIDialogItemContext context)
{
if (context == null)
{
return;
}
OnInit(context.ParentWidth, context.Content);
}
public void OnInit(float parentWidth, string content)
{
CacheReferences();
if (_rectTransform == null || _contentText == null)
{
return;
}
_contentText.text = content ?? string.Empty;
if (parentWidth > 0f)
{
_rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, parentWidth);
}
float preferredHeight = _contentText.GetPreferredValues(_contentText.text, _rectTransform.rect.width,
float.PositiveInfinity).y;
float targetHeight = Mathf.Max(_minHeight, preferredHeight);
if (_layoutElement != null)
{
_layoutElement.preferredHeight = targetHeight;
}
_rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, targetHeight);
}
public void SetContent(string content, float parentWidth)
{
OnInit(parentWidth, content);
}
private void CacheReferences()
{
if (_rectTransform == null)
{
_rectTransform = transform as RectTransform;
}
if (_contentText == null)
{
_contentText = GetComponentInChildren<TMP_Text>(true);
}
if (_layoutElement == null && _rectTransform != null)
{
_layoutElement = gameObject.GetComponent<LayoutElement>();
if (_layoutElement == null)
{
_layoutElement = gameObject.AddComponent<LayoutElement>();
}
}
if (_rectTransform != null && _minHeight <= 0f)
{
_minHeight = Mathf.Max(20f, _rectTransform.rect.height);
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e9fe74c6a0acb0a40bae49bdf039be60
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -10,7 +10,6 @@ namespace UI
/// 可拖拽拼装部件:负责拖拽交互、出生点回退与放置到槽位。
/// </summary>
[RequireComponent(typeof(RectTransform))]
[DisallowMultipleComponent]
public class CombineDraggablePart : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerEnterHandler, IPointerExitHandler
{
#region Inspector Config
@@ -4,7 +4,6 @@ using Event;
using GameFramework.Event;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using UnityGameFramework.Runtime;
namespace UI
@@ -12,7 +11,6 @@ namespace UI
/// <summary>
/// MVC UI form for GameplayA. It builds slots and draggable parts from external data.
/// </summary>
[DisallowMultipleComponent]
public class CombineForm : UGuiForm
{
#region Property
@@ -8,7 +8,6 @@ namespace UI
/// <summary>
/// 拼装槽位:接收拖拽部件并转发给玩法控制器做规则校验。
/// </summary>
[DisallowMultipleComponent]
public class CombineSlot : MonoBehaviour, IDropHandler
{
#region Inspector Config
@@ -0,0 +1,114 @@
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace UI
{
public class PlayerDialogItem : MonoBehaviour
{
[SerializeField] private TMP_Text _contentText;
[SerializeField] private Image _bg;
[SerializeField] private float _preferredWidth;
[SerializeField] private float _horizontalPadding;
[SerializeField] private float _verticalPadding;
private RectTransform _rootRectTransform;
private LayoutElement _layoutElement;
private void Awake()
{
CacheReferences();
}
public void OnInit(PlayerDialogItemContext context)
{
if (context == null)
{
return;
}
OnInit(context.Content);
}
public void OnInit(string content)
{
CacheReferences();
if (_contentText == null || _bg == null || _rootRectTransform == null)
{
return;
}
_contentText.text = content ?? string.Empty;
Vector2 unconstrainedSize = _contentText.GetPreferredValues(_contentText.text, float.PositiveInfinity,
float.PositiveInfinity);
float targetWidth = Mathf.Min(_preferredWidth, unconstrainedSize.x + _horizontalPadding);
targetWidth = Mathf.Max(_horizontalPadding, targetWidth);
float textWidth = Mathf.Max(0f, targetWidth - _horizontalPadding);
Vector2 constrainedSize = _contentText.GetPreferredValues(_contentText.text, textWidth,
float.PositiveInfinity);
float targetHeight = Mathf.Max(0f, constrainedSize.y + _verticalPadding);
RectTransform bgRect = _bg.rectTransform;
bgRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, targetWidth);
bgRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, targetHeight);
if (_layoutElement != null)
{
_layoutElement.preferredHeight = targetHeight;
_layoutElement.minHeight = targetHeight;
}
_rootRectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, targetHeight);
}
private void CacheReferences()
{
if (_rootRectTransform == null)
{
_rootRectTransform = transform as RectTransform;
}
if (_contentText == null)
{
_contentText = GetComponentInChildren<TMP_Text>(true);
}
if (_bg == null)
{
_bg = GetComponentInChildren<Image>(true);
}
if (_layoutElement == null && _rootRectTransform != null)
{
_layoutElement = gameObject.GetComponent<LayoutElement>();
if (_layoutElement == null)
{
_layoutElement = gameObject.AddComponent<LayoutElement>();
}
}
if (_contentText == null || _bg == null || _rootRectTransform == null)
{
return;
}
RectTransform bgRect = _bg.rectTransform;
RectTransform textRect = _contentText.rectTransform;
_horizontalPadding = Mathf.Max(0f, bgRect.rect.width - textRect.rect.width);
_verticalPadding = Mathf.Max(0f, bgRect.rect.height - textRect.rect.height);
if (_preferredWidth <= 0f)
{
_preferredWidth = bgRect.rect.width > 0f ? bgRect.rect.width : _rootRectTransform.rect.width;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d82051b50b7801c4f86c71e77c353f77
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -12,6 +12,8 @@ namespace UI
[SerializeField] private float _fadeDuration;
[SerializeField] private bool _allowFade = true;
private Sequence _fadeSequence;
public UnityEvent _onSelect;
@@ -21,17 +23,26 @@ namespace UI
public void OnPointerEnter(PointerEventData eventData)
{
KillFadeSequence();
_fadeSequence = DOTween.Sequence();
_fadeSequence.Append(_bgImage.DOFade(1, _fadeDuration));
if (_allowFade)
{
_fadeSequence = DOTween.Sequence();
_fadeSequence.Append(_bgImage.DOFade(1, _fadeDuration));
}
_onSelect.Invoke();
}
public void OnPointerExit(PointerEventData eventData)
{
KillFadeSequence();
_fadeSequence = DOTween.Sequence();
_fadeSequence.Append(_bgImage.DOFade(0, _fadeDuration));
if (_allowFade)
{
_fadeSequence = DOTween.Sequence();
_fadeSequence.Append(_bgImage.DOFade(0, _fadeDuration));
}
_onDeselect.Invoke();
}