Dev Diary - Project 3: Learning How to Use CSV's in Unity

For our project we will be making out levels in Google Sheets and exporting them as CSV's. I've been looking at examples of both CSV's and CSV readers on YouTube and different websites. Pretty much a CSV file is a spreadsheet converted to text, separated by commas. A CSV reader, converts that file into pretty much anything. It can be a simple sting array or even a dictionary. It depends on what sort of project you're working on, as well as how complex/flexible you want the reader to be. For our project, we're going to be reading prefab names from the CSV. So it will translate to either a normal string array, or a 2D string array, which will give us coordinates for placing the tiles. Let's look at an example of a CSV reader I found online here, and break it down.

1.PNG
 

This is a function essentially takes in a CSV file as a TextAsset and returns a 2D string array. A 2D string array would be best for grid based games, such as the one we're making. This is because the 2 index's that an element has in the array can correspond to a reference point in a grid, or as an individual tile.

2.PNG
 

Then we create a 2D string array variable called "allStringsByWord". This array will have each element corresponding to an individual word or "cell" in the CSV. Also there is another variable, this time just a normal string array called "allStringsByLine". This is then set to be each line of the CSV file. The .Split function, splits a string based on a character. In this case it was the "\n" or new line character, so each element of the array will be a line in the CSV.

3.PNG
 

Then we make the "allStringsByWord" array's row count equal to the amount of lines (or rows) in the "allStringsByLine" array.

4.PNG
 

Next, we loop through the length of the "allStringsByLine" array. Each row in the "allStringsByWord" 2D array, is having columns added. These columns are done by splitting the same corresponding element in the "allStringsByLine" array by commas (,). This essentially makes the 2D string array represent the spreadsheet layout. If there are 5 rows and 3 columns in the spreadsheet, then the array size will be [5][3]. You can then get elements from that array, for example allStringsByWord[2][1] will return the cell of string from the 2nd row, 1st column.

Our CSV loader will of course be more complex in the game. It will need to sort through each element of the 2D array, perhaps each element would also have more than 1 value. Since we have guard patrols, this may be a challenge. Either way, through looking at this CSV loader and many others, I now have a better understanding of what they are, what they do and how they do it.