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. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

String array to 2D Char Array

Discussion in 'Scripting' started by freedom667, Mar 21, 2018.

  1. freedom667

    freedom667

    Joined:
    Sep 6, 2015
    Posts:
    424
    I want to assign the strings in string array to char array. So I have to declare 2D char array because of it. I wrote this code but giving index out of range. where am I doing wrong?

    I tried for loop, foreach loop but did not work again. I deleted loops but neverthless I'm stuck here.

    this is Serializable script for 2D char array
    Code (CSharp):
    1.  [System.Serializable]
    2. public class Chars
    3. {
    4.     public char[] chars;
    5. }
    6.  
    Code (CSharp):
    1. public int length;
    2.  
    3. public string[] answers;
    4.  
    5. public Chars[] answerChars;
    6.  
    7. private void Start()
    8.     {
    9.         length = answers.Length;
    10.         answerChars = new Chars[length];
    11.     }
     
    Last edited: Mar 21, 2018
  2. jschieck

    jschieck

    Joined:
    Nov 10, 2010
    Posts:
    429
    I think your misunderstanding the fundamentals of arrays, but you need to to loop through and assign a new instance of each class. Here's how you'd do it using your code, though I'm not sure I want to know why your doing this...
    Code (CSharp):
    1.  
    2. public string[] answers;
    3. public Chars[] answerChars;
    4. private void Start()
    5. {
    6.     // initialize the array to match the size of the answers array
    7.     answerChars = new Chars[answers.Length];
    8.     // loop through each answer item
    9.     for (int i = 0; i < answers.Length; i++)
    10.     {
    11.         // create a new class and assign it's "chars" field
    12.         answerChars[i] = new Chars { chars = answers[i].ToCharArray() };
    13.     }
    14. }
    15.  
     
  3. freedom667

    freedom667

    Joined:
    Sep 6, 2015
    Posts:
    424
    Yes. I'm too misunderstanded the fundamentals of arrays. Thanks it works. I making a tetris style word game. just word matching left. I thought this might be. the letter blocks goes down like tetris and placing grids. if any word matching letters up to down or left to right, then the game will give score.