Unity3D – Text Based Map Importer

Unity3D Text Based Map Importer.

Specify Width, Height, and Prefabs to place. Map files should be placed in your Assets folder, however this can be changed via the script to use a different directory.

Text Files should be written as such:

1,1,1,1,1,1,1,1,1,1,
1,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,1,
1,1,1,1,1,1,1,1,1,1

using UnityEngine;
using System.Collections;
using System.Text;
using System.IO;

public class MapImporter : MonoBehaviour {

  public string fileNameToLoad;

  public int mapWidth;
  public int mapHeight;

  public GameObject Floor;
  public GameObject Roof;

  private int[,] spaces;

  void Awake () {
    spaces = Load (Application.dataPath + "\\" + fileNameToLoad);
    BuildMap();
  }

  void BuildMap () {
    Debug.Log("Building Map...");
    for(int i = 0; i < spaces.GetLength(0); i++) {
      for(int j = 0; j < spaces.GetLength(1); j++) {
        if(spaces[i,j] == 0) {
          GameObject tempTile = Instantiate(Floor, new Vector3(j - mapWidth, mapHeight - i, 1), Quaternion.identity) as GameObject;
          tempTile.transform.parent = GameObject.FindGameObjectWithTag("Room").transform;
        }
        if(spaces[i,j] == 1) {
          GameObject tempTile = Instantiate(Roof, new Vector3(j - mapWidth, mapHeight - i, 0), Quaternion.identity) as GameObject;
          tempTile.transform.parent = GameObject.FindGameObjectWithTag("Room").transform;
        }
      }
    }
    Debug.Log("Building Done...");
  }

  private int[,] Load(string filePath) {
    try {
      using(StreamReader sr = new StreamReader(filePath) ) {
        string input = sr.ReadToEnd();
        string[] lines = input.Split(new[] { '\r', '\n' }, System.StringSplitOptions.RemoveEmptyEntries);
        int[,] spaces = new int[lines.Length, mapWidth];
        for(int i = 0; i < lines.Length; i++) {
          string st = lines[i];
          string[] nums = st.Split(new[] {',' });
          if(nums.Length != mapWidth) {
            Debug.Log("File Split, Filling Array");
            //return null;
          }
          for(int j = 0; j < Mathf.Min(nums.Length, mapWidth); j++) {
            int val;
            if(int.TryParse(nums[j], out val )) {
              spaces[i,j] = val;
            } else {
              spaces[i,j] = 1;
            }
          }
        }
        return spaces;
      }
    }
    catch(IOException e) {
      Debug.Log(e.Message);
    }
    return null;
  }
}