I have just started using Unity and I am trying to put together a simple C# script that places the Prefabs (some 2D sprites) on pre-defined positions. The problem is, that whenever I apply the script to the prefabs and try to play the scene, Unity freezes and apparently generates an infinite loop that uses up all the memory (sometimes even giving me a black screen) and I have to force-kill the process in the task manager.
The code, however, is very simple and contains no loops at all:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DungeonTest : MonoBehaviour {
public Transform DungeonBuilder;
// Use this for initialization
void Start ()
{
Instantiate (DungeonBuilder, new Vector2 (1, 1), DungeonBuilder.rotation);
Instantiate (DungeonBuilder, new Vector2 (2, 2), DungeonBuilder.rotation);
Instantiate (DungeonBuilder, new Vector2 (3, 3), DungeonBuilder.rotation);
}
void Update()
{
}
}
It can be seen from the Hierarchy Window, that the Start() method creates several instances and the memory usage also goes up to 85%(!):
Please advise on what could have possibly gone wrong here. I have already watched several tutorial videos and I have read the relevant passages from the documentation, but I can't seem to figure this one out.
Thanks!
Your DungeonTest script should not be on the prefab you are instantiating. What's happening is that Start() gets executed every time the prefab gets instantiated.
So the first tile creates 3 new tiles. Each of those tiles now also make 3 new tiles and so forth to infinity.
Make a new object in the scene with the DungeonTile script and remove all scripts from the prefab you are instantiating.
This does not mean you can't have scripts on your prefab. Simply keep in mind that whatever is in your Start() method will execute as soon as your new instance is added to the scene.