Simple Unity Dungeon Maker Script

Untitled.png

This script is placed on a plane and creates a 15 by 15 grid of prefabs based on a csv-like file. It can be used to create a dungeon like map.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;


[System.Serializable]
public class MultiDimensionalInt
{
    public int[] intArray;
}

public class MapMaker : MonoBehaviour { 
    public bool hideWall = false;
    private bool hist = false;
    public Transform player;
    public float disappearThresh;
    public GameObject[] walls;
    public float[] yoffset;
    public float[] xoffset;
    public float[] zoffset;

    public TextAsset mapData;
    public string[][] map = new string[15][];
    
    void Start()
    {
        string[] text = mapData.text.Split('\n');
        for (int i = 0; i < map.Length; i++)
        {
            map[i] = text[i].Split(',');
        }

        if (!hideWall)
            loadWalls();
    }
    
    void Update()
    {
        if (hideWall != hist)
        {
            if (hideWall)
            {
                unloadWalls();
            } else
            {
                loadWalls();
            }
            hist = hideWall;
        }

        if (Vector3.Distance(transform.position, player.position) > disappearThresh)
        {
            hideWall = true;
        } else if (Vector3.Distance(transform.position, player.position) < disappearThresh)
        {
            hideWall = false;
        }
    }

    void loadWalls()
    {
        for (int i = -14; i <= 14; i += 2)
        {
            for (int j = -14; j <= 14; j += 2)
            {
                int res = Convert.ToInt32(map[(i + 14) / 2][ (j + 14) / 2]);
                if (res != 0)
                {
                    int index = res - 1;
                    var wall = Instantiate(walls[index], transform.position + (new Vector3(i + xoffset[index], yoffset[index], j + zoffset[index])), Quaternion.identity);
                    wall.transform.parent = transform;
                }
            }
        }
    }

    void unloadWalls()
    {
        foreach (Transform child in transform)
        {
            Destroy(child.gameObject);
        }
    }
}