Show all projects | Show more projects in the category Tech Demo's

Endless-runner Cave Generator

This project was created by Simon Karman. Published on Monday 1 July 2013. This project was viewed 1236 times.
An endless-running type of cave generation I created in Unity. It only uses 3 different segments to generate unique and random caves.


I created an endless-running type of cave generation in Unity C#. (Download at the bottom of the page!)

As seen in the image above I only uses 3 different segments to generate unique and random caves. It is really easy to create more segments and add those to the system

The core of the system is rougly 20 lines of code:
public GameObject CreateNewSegment(Connection connectedTo)
		//Create the segment
		GameObject segmentPrefab = Hierarchy.GetComponentWithTag<Picker>("SegmentPicker").Pick(segmentsSpawned).GetComponent<SegmentCollection>().GetRandomSegment();
		GameObject segmentInstance = (GameObject) Instantiate(segmentPrefab,, Quaternion.identity);
		segmentInstance.transform.parent = this.transform.parent;
		//Setup segment connections
		Segment segment = segmentInstance.GetComponent<Segment>();
		Connection otherConnection = segment.connections[Random.Range(0, segment.connections.Count)];
		if (connectedTo != null)
			otherConnection.other = connectedTo;
			connectedTo.other = otherConnection;
		//Create a segment holder at the transform of the otherConnection
		GameObject segmentHolder = new GameObject("SegmentHolder");
		segmentHolder.transform.position = otherConnection.transform.position;
		segmentHolder.transform.rotation = otherConnection.transform.rotation;
		//Setup the holder hierarchy
		segmentHolder.transform.parent = this.transform;
		segment.transform.parent = segmentHolder.transform;
		//Place segment on the connection
		if (connectedTo != null)
			segmentHolder.transform.position = connectedTo.transform.position;
			segmentHolder.transform.rotation = Quaternion.LookRotation(-connectedTo.transform.forward, connectedTo.transform.up);
		return segmentHolder;

In the image below you can see part of a generated cave. The player is in the center segments. This segment is connected to a next segment on each side. When moving to a different segment that segment will get activated and generate segments for it's connection points. The old segments that are now further away will get removed.


In the download below you can test the random cave generation yourself. A windows and a mac build are provided.
You can download this project here: Download Endless-runner Cave Generator