Free Code - Load a map from ASCII

Just wrote a bit of code that might be useful for others. It takes a fixed width ascii file and uses it to populate a scene with prefabs. Handy for all those people doing 2D/2.5D stuff for iPhone.

Web Player: http://www.jnamobile.com/asciimaploader/AsciiMapLoader.html

Turns This:

                  *     
                        
                        
                  #     
               ##       
  #*#    I              
         Y   #          
         Y              
========================

Into This:
716397--25958--$MapOne.png

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

public class AsciiMapReader : MonoBehaviour {
    
    public int tileWidth = 1;                                                                                    
    public int tileHeight = 1;
    public float xOffset = -5;                                                                                    
    public float yOffset = -5;                                                                                     
    public GameObject[] prefabs;
    public string characters;
    public string[] filePathAndName;
    public bool loadFromURL;    
    public GUIText errorText;
    
    private ArrayList mapObjects;
    private int mapWidth;    
    private string map;
    private WWW request;
    
    void Start() {
    	// Sample loading
        LoadMap(filePathAndName[0]);
        StartCoroutine(WaitForSecondsThenLoadMap(7,1));
        StartCoroutine(WaitForSecondsThenLoadMap(14,2));
    }
    
    private IEnumerator WaitForSecondsThenLoadMap(int wait, int map) {
        yield return new WaitForSeconds(wait);
        DestroyMap(0);
        LoadMap(filePathAndName[map]);        
    }
    
    public void LoadMap(string filePathAndName) {
    	if (loadFromURL) {
			StartCoroutine(AsyncLoadMap(filePathAndName));
    	} else {
	        string map = ReadMap(filePathAndName);
	        ParseMap(map);
    	}
    }
	  
    public void DestroyMap(float delay) {
    	if (mapObjects != null) {
	        foreach (GameObject gameObject in mapObjects) {
            	GameObject.Destroy(gameObject, delay);
        	}
    	}
        mapObjects = null;
    }   
       
    public string getMappingsAsString() {
        string result = "";
        for (int i = 0; i < characters.Length  i < prefabs.Length; i++) {
            result += characters[i] + " = " + prefabs[i].name;
            if (i != prefabs.Length - 1) {
                result += ", ";
            } else {
                result += ".";
            }
        }
        if (characters.Length > prefabs.Length) {
            result += " There are " + (characters.Length - prefabs.Length) + " unmapped characters.";
        } else if (characters.Length < prefabs.Length) {
            result += " There are " + (prefabs.Length - characters.Length) + " unmapped prefabs.";
        }
        return result;
    }
    
    private void ParseMap(string map) {
	float x = 0 , y = 0;		
	GameObject prefab;
	Object currentObject;	
	mapObjects = new ArrayList();			
	for (int i = 0; i < map.Length ; i++) {
            prefab = getPrefabForCharacter(map[i]);
            if (prefab != null) {
            	currentObject = GameObject.Instantiate(prefab, new Vector3((x * tileWidth) + xOffset, (y * tileHeight) + yOffset, 1), Quaternion.identity);
	                mapObjects.Add(currentObject);
    	    }
            x++;
            if (x == mapWidth) {
            	x = 0; y++;
	    }
    	}
    }

    private GameObject getPrefabForCharacter(char c) {
        for (int i = 0; i < characters.Length  i < prefabs.Length; i++) {
            if (characters[i] == c) {
                return (prefabs[i]);
            }
        }
        return null;
    }
    
    private string ReadMap(string filePathAndName) {
	        StreamReader reader = new StreamReader(filePathAndName);
        	string fileContents = reader.ReadToEnd();
    	    reader.Close();
	        mapWidth = fileContents.IndexOf("\n") + 1; 
        	return fileContents;
    }
    
    IEnumerator AsyncLoadMap(string url)
    {
    	if (request == null) {
	   		request = new WWW(url);	
    	}
        yield return request;
		if (request.error== null ) {
			mapWidth = request.text.IndexOf("\n") + 1; 
	        ParseMap(request.text);
		} else {
			Debug.Log("Error: " + request.error);
			errorText.text = "Error: " + request.error;
		}
		request = null;
    }
}

Specify your mapping using:
public GameObject[ ] prefabs;
public string characters;

They are mapped in order that they appear, you can get a description of the mapping using: getMappingsAsString().

Unmapped characters mean do nothing.

License is MIT, so you can do with it what you will. Credits or links to www.jnamobile.com are appreciated but not required.

Impressive.

Whoa.

One bump, just in case someone might find it useful :slight_smile:

Very useful.Mark it.

genius !

Good one!