如何解决使用 C# 在 uı 中显示游戏引擎的搜索百分比
我有一个程序在一个大型单词列表中搜索单词在游戏引擎中使用 C#。但我的问题是,当 UI 看起来太大的单词列表似乎被挂起时。为了防止它,我使用 UI 以便用户知道搜索了多少个单词。但问题是当搜索已经完成时 UI 会显示结果。当用户单击某个按钮时,如何让 UI 开始提供信息?提前致谢。
public int searchedTextAmount = 0;
void Start()
{
int seacrhedTextAmount = 0;
}
void Update()
{
ui.text = searchedTextAmount; // when buttonclickevent started,I like this value change while searching process in progress supplied by Search_Method
}
void Search_Method()
{
foreach (string word in words)
{
searchedTextAmount++;
//someoperations
}
}
void butonclickevent()
{
Invoke("Search_Method");
}
解决方法
您可以将 Coroutine 与 StopWatch
结合使用以中断搜索并在搜索时间过长时让一帧呈现。
类似的东西
// Tweak this according to your needs in the Inspector
[SerializeField] private float targetFramerate = 60f;
private StopWatch sw = new StopWatch();
IEnumerator Search_Method()
{
// No need for this to be a field
var searchedTextAmount = 0;
var total = words.Length;
// How long one frame may take before we force to render
// E.g. for 60fps this will 16.66666...
var millisecondsPerFrame = 1000f / targetFramerate;
sw.Restart();
foreach (string word in words)
{
searchedTextAmount++;
//someoperations
if(sw.elapsedMilliseconds >= millisecondsPerFrame)
{
// This will update the text once a frame (so only when needed) and will look like e.g.
// "Searching 50/500 (10%)
ui.text = $"Searching ... {searchedTextAmount}/{total} ({searchedTextAmount/(float)total:P0})";
// This tells Unity to "pause" this routine
// render this frame
// and continue from here in the next frame
yield return null;
sw.Restart();
}
}
sw.Stop();
}
void butonclickevent()
{
StartCoroutine (Search_Method());
}
因此,较低的 targetFrameRate
值意味着您在搜索过程中的帧速率将下降(滞后)更多。另一方面,较高的 targetFrameRate
会导致绝对实时搜索需要更长的时间。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。