Search code examples
unity-game-enginecrashinstantiation

Why my unity editor crash? with using Instantiate


I ran this code. And unity stopped. And unity gets closed after 1 to 10 min When I remove Instantiate this code works very well! How can I make this code run great?

Unity Editor.log file : https://github.com/Oein/UnityBuilds/blob/main/Editor.log.zip

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

public class MakeGround : MonoBehaviour
{
public Sprite ground;
public Sprite leftGround;
public Sprite rightGround;

string[] map = {
    "aaaaaaaaaa",
    "aaaaaaaaaa",
    "aaaaaaaaaa",
    "zxxxxxxxxc"
};
// Start is called before the first frame update
void Awake()
{
    for (int y = 0; y < map.Length; y++)
    {
        for (int x = 0; x < map[0].Length; x++)
        {
            print(x.ToString() + "  At  " + y.ToString());
            this.transform.position = new Vector3(x, y, 0);
            if (map[map.Length - 1 - y][x] != 'a')
            {
                Instantiate(gameObject , transform);
            }

        }
    }
}

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

}
}

Solution

  • You are instantiating gameObject which is the object this script is attached to itself!

    So what happens is:

    • The first Awake is called
    • You instantiate n times gameObject
    • The n new objects also have this script MakeGround attached
    • So another n times Awake is called
    • You spawn n x n times gameObject
    • ..... => Infinite exponential instantiation

    You probably would rather use a dedicated separate Prefab which doesn't have that script attached and reference it via e.g.

    [SerializeField] GameObject prefabToInstantiate;
    

    and then do

    Instantiate(prefabToInstantiate, transform);