The game runs on a loop creating infinite copies through instantiate. What am I doing wrong?

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

public class Triangle : MonoBehaviour {

    private int places = 0;

    // Use this for initialization
    void Start () {
        // Instantiating places
        createPlaces(3);

    }


    // Update is called once per frame
    void Update () {

    }

    void createPlaces(int places) {
        this.places = places;
        for (int i = 0; i <= places; i++) {
            Instantiate (this);
        }
    }

So, I’m not sure whats wrong. My intention was to create 3 triangles on the screen. But the game runs on an infinite loop creating the gameObject. Also, I notice many people do not instantiate things by referencing (this). Is there anything wrong with that? Or should I do: Instantiate(gameObject).

Thanks for the help. :slight_smile:

Every time you create a Triangle object, it calls createsPlaces(3), which creates 3 Triangle objects, that calls createPlaces(3) which creates 3 Triangle objects, that calls createPlaces(3) which creates 3 Triangle objects, that calls createPlaces(3) which creates 3 Triangle objects, that calls createPlaces(3) …

I think you see where I’m going with this :slight_smile:

2 Likes

Exponential instantiation!

Calling Instantiate(this) in Start is a bad idea. You probably want to move all of this logic to a different GameObject.

1 Like

Paraphrasing @Kiwasi , Instead of letting the triangle instantiate new ones, you could make a new class (e.g. TriangleManager ) responsible for instantiating the triangles.

1 Like