Tyler Shelby
Tyler Shelby

Reputation: 11

Why is this code cutting out the last line in text?

In the file below, I use the video that you can find here to make a type-writer effect on screen. I'm having a bit of an issue with it at this time.
For whatever reason, it's cutting off the last letter whenever I use it (i.e. putting in "Hello there" types out "Hello ther"). Any ideas on why this is happening?

The programming I am using is a modified version to fit my game:

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);
    }
}

}

Upvotes: 0

Views: 39

Answers (1)

David
David

Reputation: 34573

Your for loop is looping from 0 to Length - 1. Then you are using this variable to tell Substring the number of characters to return. It returns 0 characters the first time. At the end, it returns all but the last character.

You can either add 1 to the length argument, or change the bounds of your for loop:

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

Upvotes: 3

Related Questions