How can I generate random paths which are connected to each other through nodes in Unity C#?

For example, I want to generate paths like this image:

enter image description here

I have tried this code:

public class PointCreator : MonoBehaviour {
    public GameObject cube;
    public int numberOfCubes=6;
    public int min, max;
    private LineRenderer line;          
    List<GameObject> collidedObjects = new List<GameObject>();

    void Start () {
        PlaceCubes ();
        line = this.gameObject.AddComponent<LineRenderer>();
        line.SetWidth(1F, 1F);

        if (collidedObjects.Count > 0) {
            for (int i = 0; i < collidedObjects.Count; i++) {
                print ("line" + collidedObjects[i].name);
                line.SetPosition (0, collidedObjects [0].transform.position);
                line.SetPosition (1, collidedObjects [1].transform.position);

    Vector2 GeneratedPosition() {
        int x,y;
        x = Random.Range(min,max);
        y = Random.Range(min,max);

        return new Vector2(x,y);

    void PlaceCubes() {
        for(int i = 0; i < numberOfCubes; i++) {
            GameObject obj = Instantiate(cube, GeneratedPosition(), transform.rotation);// Quaternion.identity
            collidedObjects.Add (obj);

In this code I generated GameObjects at random places and add all objects in list and then I want to create lines between all GameObjects, but don't understand how to do that.

Now my result is like this:

enter image description here

  • \$\begingroup\$ Welcome to GDSE. What criteria are you using to determine if two nodes should be connected or not? \$\endgroup\$ – Pikalek May 8 '19 at 2:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.