Home > Software engineering >  Script to instantiate an object is crashing unity
Script to instantiate an object is crashing unity

Time:06-07

I am trying to make a moving platform with frequent holes in it, so I figured one way to do that would be to make a block the size of the hole I want there to be and duplicate it across the screen. When one block leaves the scene it is teleported to the other side and goes across again. (I haven't done this yet), and then every so often have one block not show to create a hole.

I suppose I could create 12 blocks individually in the unity editor, but I am making this game with a couple of friends and want to avoid clutter. When I attach the script to the block I want to duplicate and run the project, the whole editor freezes and I have to close it via the task manager.

Here is the code causing issues ( only the start function, update() is empty for now.).

 void Start()
    {

        for (int i = 0; i < 12; i  )
        {
            Instantiate(transform, new Vector2(transform.position.x   (i * 1), transform.position.y), transform.rotation);
        }

    }

If anyone has any ideas about why this might be happening I would appreciate it. Thank you.

CodePudding user response:

This problem is because you are replicating the object itself at start() and at the instantiate moment the clone object, the clone that has this script will start replicating again and this cycle will continue until your system stack overflow will be. To solve the problem, you must delete this script before instantiate.

Destroy(this);
for (int i = 0; i < 12; i  )
{
    Instantiate(transform, new Vector2(transform.position.x   (i * 1), transform.position.y), transform.rotation);
}
  • Related