I wrote a script that uses cellular automata to create a cave system for my game, however, whenever I attempt to run the script Unity crashes.
using UnityEngine;
using System;
class MapGen : MonoBehaviour
{
public Transform wall;
public int[] dimentions = new int[] {25, 25};
public float chanceToStartAlive = 0.45f;
public int numberOfSteps = 2;
public int birthLimit = 4, deathLimit = 3;
private bool[,] cellmap;
private bool[,] initializeMap (bool[,] map)
{
Debug.Log ("initializeMap");
for (int x = 0; x < dimentions[0]; x++) {
for (int y = 0; y < dimentions[1]; y++) {
if (UnityEngine.Random.value < chanceToStartAlive) {
map [x, y] = true;
}
}
}
return (map);
}
private int countAliveNeighbors (bool[,] map, int x, int y)
{
Debug.Log ("countAliveNeighbors");
int count = 0;
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; i++) {
int neighbor_x = x + i;
int neighbor_y = y + j;
if (i == 0 && j == 0) {
} else if (neighbor_x < 0 || neighbor_y < 0 || neighbor_x >= map.GetLength (0) || neighbor_y >= map.GetLength (1)) {
count += 1;
}
}
}
return (count);
}
private bool[,] doStep (bool[,] oldMap)
{
Debug.Log ("doStep");
bool[,] newMap = new bool[oldMap.GetLength (0), oldMap.GetLength (0)];
for (int x = 0; x < dimentions[0]; x++) {
for (int y = 0; y < dimentions[1]; y++) {
int nbs = countAliveNeighbors (oldMap, x, y);
if (oldMap [x, y]) {
if (nbs < deathLimit) {
newMap [x, y] = false;
} else {
newMap [x, y] = true;
}
} else {
if (nbs > birthLimit) {
newMap [x, y] = true;
} else {
newMap [x, y] = false;
}
}
}
}
return (newMap);
}
private void Start ()
{
Debug.Log ("Start");
cellmap = new bool[dimentions [0], dimentions [1]];
cellmap = initializeMap (cellmap);
int count = 0;
if (count < numberOfSteps) {
if (GameObject.FindGameObjectsWithTag ("wall").Length != 0) {
foreach (GameObject go in GameObject.FindGameObjectsWithTag("wall")) {
Destroy (go);
}
}
for (int x = 0; x < dimentions[0]; x++) {
for (int y = 0; y < dimentions[1]; y++) {
if (cellmap [x, y]) {
Instantiate (wall, new Vector2 (x, y), Quaternion.identity);
}
}
}
cellmap = doStep (cellmap);
} else {
Debug.Log ("Disabled");
this.enabled = false;
}
}
}
↧