Search code examples
c#unity-game-engineinstantiation

Unity Freezes When I Press The Play Button With The Instantiate Syntax C#


Every time I press the play button in unity it just sits there doing nothing and I think it has something to do with the Instantiate Syntax here is my code and this is the only script I have running. I'm trying to just simply make a grid of my GameObject. if anyone knows why that would be great or if not maybe you know a better way to do it. Thanks!!

    using UnityEngine;

public class Script2 : MonoBehaviour
{
    public GameObject Sprite;

    void Start()
    {
        Generate();
    }
    public void Generate()
    {
        float width = Sprite.transform.lossyScale.x;
        float height = Sprite.transform.lossyScale.y; 
        for (int y = 0; y <= 100; y += 10)
        {
           for (int x = 0; x <= 100; y += 10)
            {
                GameObject Square = Sprite;
                Instantiate(Square, new Vector2(x * width, y * height), Quaternion.identity);
            }
        }
    }
}

Solution

  • Your x loop has an error, so it ran into infinite loop. Should be x+=10

    for (int x = 0; x <= 100; x += 10)
    {
        GameObject Square = Sprite;
        Instantiate(Square, new Vector2(x * width, y * height), Quaternion.identity);
    }