Weird behavior of prefabs generated and saved in a folder using C# script
I'm trying to generate a grid of square planes ("tiles") for my game. My goal is to generate instances of the tile prefab using a script and automatically save them inside a folder.
I prepared a prefab for a single tile and I'm trying to use the following code:
void GenerateSquare(int side_length){
int counter = 0;
int i = 0;
while(i < side_length){
int j = 0;
while(j < side_length){
GameObject new_tile = Instantiate(TILE_PREFAB);
new_tile.transform.position = new Vector3Int(i, 0, j);
new_tile.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
Object prefab = PrefabUtility.CreateEmptyPrefab("Assets/Arena_20x20_prefabs/"+new_tile.gameObject.name+i+j+".prefab");
PrefabUtility.ReplacePrefab(new_tile.gameObject, prefab, ReplacePrefabOptions.ConnectToPrefab);
print ("created " + counter);
print ("position " + i + "," + j);
counter++;
j++;
}
i++;
}
}
The result of running the game in Unity Editor is pretty weird.
In the game preview screen I can see a nice 20x20 grid of tiles. Everything seems to be generated correctly:
Then I go to the Hierarchy tab and notice that something might not be right. The text of most tiles that land in the hierarchy tab is formatted in blue, but there are 10 tiles formatted in red (coordinates (1,10) to (1,19))
After I stop the game preview and go to the "Arena_20x20_prefabs" folder, I can only find 390 objects there. The ten previously highlighted in red are missing. After moving the 390 objects to the scene, the grid looks like this:
Does anyone have any idea what goes wrong here?