Search code examples
c#arraysunity-game-engineunityscript

how to convert two dimensional integer array elements into string in c#?


i would like to save my grid positions of 4*4 grid with integer before quitting game.

I thought i could convert array into string and save it using player preferences for next use.

i saved the numbers in two dimensional integer array. now how to convert it into string in c#.


Solution

  • You can use StringBuilder when you convert your array into string. You can split every element in row by "," (or any other symbol) and rows can be splited by "." (or any other symbol), so when you will parse string to int[,] array you don't need to know the array sizes:

    public string ArrayToString(int[,] toConvert)
    {
        StringBuilder sb = new StringBuilder();
    
        for (int a = 0; a < toConvert.GetLength(0);a++)
        {
            for (int b = 0; b < toConvert.GetLength(1);b++)
            {
                sb.Append(toConvert[a,b].ToString() + ",");
            }
    
            sb.Append(".");
        }
    
        return sb.ToString();
    }
    

    Then you can restore your array from string:

    public int[,] ArrayFromString(string toConvert)
    {
        string[] rows = toConvert.Split('.');
        string[] elements = rows[0].Split(',');
    
        int[,] result = new int[rows.Length, elements.Length];        
    
        for (int a = 0; a < rows.Length; a++)
        {
            string[] items = rows[a].Split(',');
    
            for (int b = 0; b < items.Length; b++)
            {
                result[a,b] = Convert.ToInt32(items[b]);
            }
        }       
    
        return result;
    }