【问题标题】:Why is this code cutting out the last line in text?为什么这段代码会删除文本的最后一行?
【发布时间】:2023-04-02 04:01:01
【问题描述】:

在下面的文件中,我使用视频that you can find here 在屏幕上制作打字机效果。我现在遇到了一些问题。
无论出于何种原因,每当我使用它时,它都会切断最后一个字母(即输入“Hello there”会输出“Hello ther”)。关于为什么会发生这种情况的任何想法?

我正在使用的编程是一个修改版本以适合我的游戏:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class TypeWriterEffect : MonoBehaviour {

public float delay = 0.1f;
public float startDelay = 0f;
public string fullText;
public bool showGameHS;
public bool showTotalScore;
public string totalGameScore;
private string currentText = "";

// Use this for initialization
void Start () {
    totalGameScore = PlayerPrefs.GetString("totalGameScore"); // total score throughout the game
    if (showTotalScore)
    {
        fullText = TimerScript.fullScore.ToString() + "."; // a "." is added to fix this issue
    }
    else if (showGameHS) // the local highscore
    {
        fullText = totalGameScore + "."; // a "." is added to fix this issue
    }
    StartCoroutine(ShowText());
}

IEnumerator ShowText(){
    yield return new WaitForSeconds(startDelay); // this was added on as a basic start delay

    for (int i = 0; i < fullText.Length; i++){
        currentText = fullText.Substring(0,i);
        this.GetComponent<Text>().text = currentText;
        yield return new WaitForSeconds(delay);
    }
}

}

【问题讨论】:

  • i &lt; fullText.Length 总是在字符串的完整长度之前停止一个索引 -> 最后一个符号的子字符串切割

标签: c# unity3d user-interface text


【解决方案1】:

您的for 循环正在从0 循环到Length - 1。然后你使用这个变量告诉Substring 要返回的字符数。它第一次返回 0 个字符。最后,它返回除最后一个字符之外的所有字符。

您可以将长度参数加 1,或者更改 for 循环的边界:

for (int length = 1; length <= fullText.Length; length++){
    currentText = fullText.Substring(0, length);
    this.GetComponent<Text>().text = currentText;
    yield return new WaitForSeconds(delay);
}

【讨论】:

    猜你喜欢
    • 2012-12-23
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    相关资源
    最近更新 更多