Search Unity

String-Array toCharArray broken?

Discussion in 'Scripting' started by JimKnoxx, Jun 6, 2018.

  1. JimKnoxx

    JimKnoxx

    Joined:
    Jun 10, 2015
    Posts:
    5
    I just encountered some strange behavior.
    I am creating a string[], each index containing 16x '0'. Then I want to change that char to a different type as a spawning list.
    I run the script. And got an nullpointer exception. So I started debugging. I do not understand how this is happening:
    Note: I switched to .net 4.5 in Unity, is this causing it?


    Code (CSharp):
    1.         spawnList = new string[val.level * 2 + 10];
    2.         for (int i = 0; i < spawnList.Length; i++) {
    3.             for (int j = 0; j < 16; j++) {
    4.                 spawnList[i] += "0";
    5.             }
    6.         }
    7.         char[] tmp;
    8.         int badLuck = 10;
    9.         int count = 1;
    10.         while (maxCoins > 0) {
    11.             int start = Random.Range(1, 4);
    12.             int step = Random.Range(1, 4);
    13.             for (int i = start; i < val.level * 2 + 10; i += step) {
    14.                 for (int j = 0; j < 16; j++) {
    15.                     Debug.Log(i + " " + j + " " + spawnList[i] +  "  " + spawnList[i][j]);
    16.                      [......]
    It created this output:


    I also tryed
    Debug.Log(i + " " + j + " " + spawnList[i] +  "  " + spawnList[i][j]);

    Debug.Log(i + " " + j + " " + spawnList[i] +  "  " + spawnList[i].toCharArray()[j]);

    Debug.Log(i + " " + j + " " + spawnList[i].toString() +  "  " + spawnList[i].toCharArray()[j].toString());
     
  2. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
    The problem is probably in the part you didn't list.
     
  3. JimKnoxx

    JimKnoxx

    Joined:
    Jun 10, 2015
    Posts:
    5
    Yea... I just discoverd that a char[] var with .toString() will in fact return System.Char[] and not the char[] as string...

    Had:
    Code (CSharp):
    1. char[] tmp = spawnList[i].ToCharArray();
    2. tmp[j] = 'g';
    3. spawnList[i] = tmp.toString();
    Correct:
    Code (CSharp):
    1. char[] tmp = spawnList[i].ToCharArray();
    2. tmp[j] = 'g';
    3. spawnList[i] = new string(tmp);
     
  4. kru

    kru

    Joined:
    Jan 19, 2013
    Posts:
    452
    Code (csharp):
    1. char[] bar = new char[10];
    2. var baz = bar.ToString();
    3. Debug.Log(baz.GetType());
    prints out System.String.