Why this makes Unity crash?
This makes my Unity aplication crash, i want to generate blocks in my Unity2D proyect with a sprite in the SpriteRenderer in my spritesheet. I want to be able to configurate the block size and the width and the geight of the generation, please, help.
using UnityEngine;
public class WorldGenerator : MonoBehaviour
{
public int width = 100;
public int height = 100;
public GameObject[] blocks;
public Sprite[] _sprite;
public int blockSize = 3;
public int typeOfBlock = 5;
private void Start()
{
_sprite = Resources.LoadAll<Sprite>("Tiles");
blocks = new GameObject[width * height];
for (int blockNum = 0; blockNum < blocks.Length; blockNum++) {
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
blocks[blockNum] = new GameObject("Tile" + blockNum);
blocks[blockNum].transform.position = new Vector3(x,y,0);
blocks[blockNum].transform.localScale *= blockSize;
blocks[blockNum].AddComponent<SpriteRenderer>();
blocks[blockNum].GetComponent<SpriteRenderer>().sprite = _sprite[typeOfBlock];
}
}
}
}
}
Answer by webcam · Jun 27, 2017 at 04:26 PM
You don't want that first loop to be running for blocks.Length, you are adding blocks in that loop so blockNum will never be greater than the length. You only need the two nested for loops to fully populate your array. Try this:
private void Start()
{
_sprite = Resources.LoadAll<Sprite>("Tiles");
blocks = new GameObject[width * height];
int blockNum = 0;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
blocks[blockNum] = new GameObject("Tile" + blockNum);
blocks[blockNum].transform.position = new Vector3(x,y,0);
blocks[blockNum].transform.localScale *= blockSize;
blocks[blockNum].AddComponent<SpriteRenderer>();
blocks[blockNum].GetComponent<SpriteRenderer>().sprite = _sprite[typeOfBlock];
blockNum++;
}
}
}
Right.
btw, the original code would create 10000 times 10000 objects so that's 100 million gameobjects.
Answer by ankushkumar · Jun 28, 2017 at 05:55 AM
It may be crash sometimes if you are changing or implementing the script on play mode time.
Your answer
Follow this Question
Related Questions
Can't add script to anything. 1 Answer
How to teleport a car? 1 Answer
Storing levels data 1 Answer
Trying to simulate SNES party snake, non-grid. 0 Answers
[HELP] How to lock input key? 1 Answer