String.Length returns '1' when string is much longer.

Hey,

Working on a message system from NPCs I wanted the message to pop up, write all the text, then wait five seconds before closing. I’ve had trouble with the last part and though I could get the effect by checking if the amount of letters written to the text box is equal to the length of the message, then waiting five seconds and closing.

My issue is that when I get the length of the message to display, it only sets it to ‘1’ even though my test message is 110 characters long. After some debugging, I’ve found that displaying the string in debug only displays the first letter, however, it still displays in my text box correctly. Does anyone know why this is happening/how to fix it?

Code:

	public float letterPause = 0.2f;
	public AudioClip sound;
	public UnityEngine.UI.Text textScript;
	public GameObject masterText;
	public int msgLength;
	
	public string message;
	
	// Use this for initialization
	void Start () 
	{
		//textScript = gameObject.GetComponent<UnityEngine.UI.Text>();
		msgLength = textScript.text.Length;
		message = textScript.text;
		
		textScript.text = "";
		print ("Start Wait Meth");
		StartCoroutine (TypeText ());


	}
	public IEnumerator TypeText () 
	{

		int i = 0;// used for getting the amount of characters written to the text box.
		foreach (char letter in message.ToCharArray()) 
		{
			i++;
			print(i.ToString() + "/" + message.Length);
			textScript.text += letter;
			if (sound) // Just for playing the speaking audio- Random blips.
			{
				float pitch = Random.Range (0.6f,1.25f);
				audio.pitch = pitch;
				audio.PlayOneShot (sound);
			}
			yield return new WaitForSeconds(letterPause);
			if(i == message.Length)
			{
				print ("Now Waiting");
				yield return new WaitForSeconds(5);
				print ("Wait Over");
				masterText.SetActive (false); // Close Text box
				i = 0;				
			}
		}
	}

Note: While writing this I did simulate what I want by changing " if(i == message.Length) " to " if(i == 110) " which shows everything else is working, just that my string is for some reason seen as 1 long when checked.

Thanks.

When you’re checking your message length, only 1 update has passed. Therefore your message only has a length of the 1st character fed into it. At this time message.length is equal to i which is 1, so your mastertext is set to masterText.SetActive (false). and i is set back to 0.

What you need to do is check if message.length == fullMessage.length (you’ll need to create a variable for this and set it to the intended messages length).

Hope this helps.