Unity Genshin Text-to-Speech: 使用 GenshinSettings 配置语音合成
Unity Genshin Text-to-Speech: 使用 GenshinSettings 配置语音合成
本指南将介绍如何在Unity中使用GenshinTextToSpeech脚本实现原神风格的文本转语音功能,并使用GenshinSettings配置API域名。
问题描述
当运行GenshinTextToSpeech脚本时,你可能会遇到以下错误:
ArgumentException: GetComponent requires that the requested component 'GenshinSettings' derives from MonoBehaviour or Component or is an interface.
UnityEngine.Component.GetComponent[T] () (at <90585cf0c5a24f279207485a8de593e7>:0)
GenshinTextToSpeech.Awake () (at Assets/AIChatTookit/Scripts/TTS&&STT/Genshin/GenshinTextToSpeech.cs:50)
原因分析
这个错误是由于 GenshinSettings 类没有继承自 MonoBehaviour 或 Component 所导致的。GetComponent<T> 方法要求请求的组件必须是 MonoBehaviour 或 Component 的子类或接口。
解决方案
为了解决这个问题,你需要修改 GenshinSettings 类,使其继承自 MonoBehaviour 或 Component。
修改 GenshinSettings 类
将 GenshinSettings 类改为继承自 ScriptableObject,并在Unity中创建 GenshinSettings 的实例,并将其作为资源文件保存。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "GenshinSettings", menuName = "ScriptableObjects/GenshinSettings")]
public class GenshinSettings : ScriptableObject
{
public string apiDomain;
}
使用 GenshinSettings
在 GenshinTextToSpeech 脚本中,你需要获取 GenshinSettings 实例并使用其 apiDomain 属性。
using System;
using System.Collections;
using System.Xml.Linq;
using UnityEngine;
using UnityEngine.Networking;
public class GenshinTextToSpeech : TTS
{
// ... 其他代码 ...
private GenshinSettings m_GenshinSettings;
private void Awake()
{
// 使用 Resources.Load 加载 GenshinSettings 实例
m_GenshinSettings = Resources.Load<GenshinSettings>("GenshinSettings");
// 如果无法加载,则输出错误日志
if (m_GenshinSettings == null)
{
Debug.LogError("无法加载 GenshinSettings 实例");
return;
}
m_PostURL = string.Format("https://{0}/api", m_GenshinSettings.apiDomain);
}
// ... 其他代码 ...
}
总结
通过将 GenshinSettings 类改为继承自 ScriptableObject 并使用 Resources.Load 方法加载实例,你就可以解决 GetComponent 方法的错误,并使用 GenshinSettings 配置 API 域名。
注意
- 请确保
GenshinSettings的实例已保存到Resources文件夹中,并且文件名与Resources.Load方法中的文件名一致。 - 如果你需要在脚本运行时动态修改
GenshinSettings的值,可以使用PlayerPrefs或其他数据存储方式来保存和加载数据。
希望这篇指南能够帮助你解决问题,并成功实现原神风格的文本转语音功能。
原文地址: https://www.cveoy.top/t/topic/jOYM 著作权归作者所有。请勿转载和采集!