Reputation: 566
Here's the setup:
Where base is a gameobject with an image:
and pixel is a 1x1 white dot.
And the code for a Cell:
using UnityEngine;
using UnityEngine.UI;
public class Cell : MonoBehaviour
{
private void Start()
{
GetComponent<Image>().color = Random.ColorHSV(0f, 1f, 0f, 1f, 0f, 1f);
}
}
Code for the Grid:
public class Grid
{
public Grid(int width, int height, float cellSize, Cell CellPrefab, Canvas canvas)
{
this.cellSize = cellSize;
oneCell = CellPrefab;
gridArray = new int[width,height];
cellContentArray = new Cell[width,height];
for (var x = 0; x < Width; x++)
{
for (var y = 0; y < Height; y++)
{
CreateCell(x, y, GetWorldPosition(x,y) + new Vector2(cellSize,cellSize)*0.5f, canvas);
}
}
}
private void CreateCell(int x, int y, Vector2 position, Canvas canvas)
{
var cell = Object.Instantiate(oneCell, position, Quaternion.identity, canvas.transform);
cell.transform.localPosition = position;
cell.name = $"[{x},{y}]";
cellContentArray[x, y] = cell;
}
private Vector2 GetWorldPosition(int x, int y)
{
return new Vector2(x * cellSize - (Width*cellSize/2f),y * cellSize - (Height*cellSize/2f));
}
}
Note that the objects that the grid contains of will never be moved, resized or otherwise translated and are thus static.
The challenge is that the size of the grid is unmangeable. In my use-case I can go no lower than a 100 by 100 grid. This means that using my current method I'm instantiating 10.000 gameObjects just to show the grid and I'm rendering 40.000 tris at this point. The Unity Editor is unresponsive for a long time when trying to select any of the cells in the grid.
As you can see on the screenshot, each cell is only a square image with a color (randomized).
I would appreciate some pointers or ways of dealing with a large amount of gameobjects in Unity or if there is a whole other way I can go about this problem. Maybe a way to "squash" all the images to one big but still keep information about the different cell positions and object information.
Thanks!
Upvotes: 0
Views: 1413
Reputation: 3861
I think rendering this through UI is the wrong abstraction.
You need to think of it this way:
These are two very different problems, and you're conflating them.
In a simple 2d Array.
You have a Cell
class.
Each cell should probably have a display color as a public property of the Cell class.
Then, your grid of cells is just a Cell[,]
object.
Create a black image with same dimensions as 2D cell array Loop through your 2D cell array.
for each x,y cell, you change the image's x,y pixel color to the cell's color.
Done. Now you have 1 game object, an image of the same dimensions as your 2D array.
Upvotes: 1