I'm trying to use the following code to read a text file stored in the Resources folder or in a file on my computer, and instantiate objects in a Unity 3D scene accordingly. I'm having trouble getting it to work. I've tried attaching the script to either the main camera or an empty gameobject. Neither work so far...
I either end up with an error saying the path does not exist (when I put the text file into the project folder on my desktop), or a null exception, or that the path contains invalid characters.
Where am I going wrong?
I'm trying to use a jagged array because I'll need users to eventually be able to change the text file on-the-go to create a level.
The text file contains the following data: S 0 0 0 1 0 0 1 0 2 2 0 0 2 1
My script currently reads:
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
using System.Linq;
using System.IO;
using UnityEngine.UI;
public class GenerateLevel : MonoBehaviour {
public Transform player;
public Transform ground;
// public Transform floor_valid;
public Transform floor_obstacle;
//public Transform floor_checkpoint;
//public const string sfloor_valid = "0";
public const string sfloor_obstacle = "0";
// public const string sfloor_checkpoint = "2";
public const string sstart = "S";
public string textFile = "maze";
string textContents;
// Use this for initialization
void Start () {
Instantiate(ground);
TextAsset textAssets = (TextAsset)Resources.Load(textFile);
textContents = textAssets.text;
//string[] lines = System.IO.File.ReadAllLines("//maze.txt");
//string textFile;
//textFile = Resources.Load("assets/resources/maze").ToString();
string[][] jagged = ReadFile(textContents);
for (int y = 0; y < jagged.Length; y++)
{
for (int x = 0; x < jagged[0].Length; x++)
{
switch (jagged[y][x])
{
case sstart:
//Instantiate(floor_valid, new Vector3(x, 0, -y), Quaternion.identity);
Instantiate(player, new Vector3(0, 0.5f, 0), Quaternion.identity);
break;
//case sfloor_valid:
// Instantiate(floor_valid, new Vector3(x, 0, -y), Quaternion.identity);
//break;
case sfloor_obstacle:
Instantiate(floor_obstacle, new Vector3(x, 0, -y), Quaternion.identity);
break;
//case sfloor_checkpoint:
// Instantiate(floor_checkpoint, new Vector3(x, 0, -y), Quaternion.identity);
//break;
}
}
}
}
// Update is called once per frame
void Update () {
}
string[][] ReadFile(string file)
{
string text = System.IO.File.ReadAllText(file);
string[] lines = Regex.Split(text, "\r\n");
int rows = lines.Length;
string[][] levelBase = new string[rows][];
for (int i = 0; i < lines.Length; i++)
{
string[] stringsOfLine = Regex.Split(lines[i], " ");
levelBase[i] = stringsOfLine;
}
return levelBase;
}
}