Files
aibis-dream/Assets/Scripts/Test/OptionTest.cs
T
2024-09-05 02:44:23 +08:00

94 lines
3.1 KiB
C#

using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;
using Yarn.Unity;
namespace AibisDream.Test
{
public class OptionTest : MonoBehaviour
{
private GameObject panel;
private GameObject prefab;
private GameObject[] buttonGroup;
private YarnOption[] _options;
void Start()
{
// 初始化时注册Command
// 第一个参数为[command name=xxx]的参数
// 第二个参数是注册的函数,在Yarn走到选择项时触发
DialogController.Instance.RegisterOptionCommand("show_buttons", ShowButtons);
// 不重要
panel = transform.GetChild(0).gameObject;
prefab = Resources.Load<GameObject>("Prefabs/UI/Choice Button");
}
/// <summary>
/// 注册的命令
/// </summary>
/// <param name="options">触发时提供的选择项</param>
public void ShowButtons(YarnOption[] options)
{
// 将前两个选项生成清单
buttonGroup = InstantiateButtons(options);
_options = options;
}
private GameObject[] InstantiateButtons(YarnOption[] options)
{
// 这里默认是前两个选项生成按钮,你也可以利用Text或Index来判断哪些是需要生成按钮的选项
GameObject[] res = new GameObject[2];
for (int i = 0; i < 2; i++)
{
var option = options[i];
var instance = Instantiate(prefab, panel.transform, true);
var textMesh = instance.GetComponentInChildren<TextMeshProUGUI>();
textMesh.text = option.Text;
instance.GetComponent<Button>().onClick.AddListener(() => {
// 执行SelectOption(), 对话就会从对应的选项往下继续执行
option.SelectOption();
});
res[i] = instance;
}
return res;
}
public void OnDestroy()
{
// 注意在合适的时机移除命令
DialogController.Instance?.RemoveOptionCommand("show_buttons");
}
[YarnCommand("change_button_name")]
public void ChangeButtonName(float idx, string buttonName)
{
var realIdx = Mathf.RoundToInt(idx);
GameObject targetButton = buttonGroup[realIdx];
var textMesh = targetButton.GetComponentInChildren<TextMeshProUGUI>();
textMesh.text = buttonName;
var button = targetButton.GetComponentInChildren<Button>();
button.onClick.RemoveAllListeners();
button.onClick.AddListener(() =>
{
var option = _options[realIdx + 2];
DialogController.Instance.TryGetVariable($"$visitedState{realIdx + 1}", out bool visitedState);
if (visitedState)
{
option.SelectOption();
}
});
}
}
}