Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Resolved string.Length and/or stringbuilder.Length always returning 0

Discussion in 'Scripting' started by Asaioki, Jun 8, 2020.

  1. Asaioki

    Asaioki

    Joined:
    Aug 1, 2016
    Posts:
    43
    Hey there,

    I'm currently stuck on something I can't wrap my head around, would someone be able to explain why this debug.Log returns 0 as a value, throwing a nullreference directly after.

    Code (CSharp):
    1. string test = "";
    2.         for (int i = 0; i < names.lastNames.Count; i++)
    3.         {
    4.             if (names.lastNames[i].lastName.prefix != "") //if the prefix is not empty
    5.             {
    6.                 test += names.lastNames[i].lastName.prefix; //add it
    7.  
    8.                 Debug.Log(test.Length); // Returns 0 ?
    9.                 if (test[test.Length - 1] == ' ') // Throws nullreference
    10. ......
    The same happens when trying to do this with stringbuilder.Append, stringbuilder.Length returns 0 and nullreference on the stringbuilder.Length when trying to check it.
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    What happens if you print out the value of "names.lastNames.lastName.prefix"?
     
    Asaioki likes this.
  3. Asaioki

    Asaioki

    Joined:
    Aug 1, 2016
    Posts:
    43
    Well thanks appearently that threw a null. I was convinced that prefix was always either "" or some actual string, turns out it was able to be null as well.