- Home /
This question was
closed Jan 04, 2017 at 10:04 AM by
Eric5h5.
Question by
BigYellow333 · Jan 04, 2017 at 09:58 AM ·
draw calls
Too many cubes in my program, and FPS is low...
Hi guys, I have a program which could generate cubes infinitely, this is it:
using UnityEngine; using System.Collections;
public class GOL: MonoBehaviour {
private bool[,] grid;
// X Size of grid
public int rows = 10;
// Density of initial random squares
public int density = 5;
// Speed of animation
public int speed = 10;
// Current row
private int currentRow = 0;
public GameObject prefabCube;
// Use this for initialization
void Start () {
grid = new bool[rows, rows];
// [. . .]
// [. . .]
// [. . .]
// Iterate over the rows in order to randomly choose cubes to turn on.
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < rows; j++)
{
//
grid[i, j] = Mathf.Floor(Random.value * density) == 0;
//GameObject.CreatePrimitive(PrimitiveType.Cube);
}
}
}
// Update is called once per frame
void Update () {
// Every speed number of frames we add another row
if (Time.frameCount % speed == 0)
{
// Tick the game of life
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < rows; j++)
{
// Get the indices of the adjacent cubes
int[,] indices = new int[8, 2]{ { j , i + 1 },
{ j + 1, i + 1 },
{ j + 1, i },
{ j + 1, i - 1 },
{ j, i - 1 },
{ j - 1, i - 1 },
{ j - 1, i },
{ j - 1, i + 1 } };
// Check to see if these cubes exist
int count = 0;
for(int k = 0; k < 8; k++)
{
int x = indices[k, 0];
int y = indices[k, 1];
if ( x < 0
|| y < 0
|| x > (rows - 1)
|| y > (rows -1))
{
continue;
}
if(grid[x, y])
{
count++;
}
}
if(grid[j, i])
{
// cell is currently alive
if(count < 2)
{
// Die
grid[j, i] = false;
} else if( count > 3 )
{
grid[j, i] = false;
}
} else
{
// cell is currently dead
if (count == 3)
{
grid[j, i] = true;
}
}
}
}
// Add row
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < rows; j++)
{
// Check if this cube is alive
if(grid[i,j] == true)
{
// get position of cube
// generate cube
Vector3 position = new Vector3(j, 0, i);
GameObject cube = prefabCube;
// Add to parent before setting global position
cube.transform.SetParent(gameObject.transform);
cube.transform.position = position;
}
}
}
// Move structure up
gameObject.transform.position += new Vector3(0, 0.5f, 0);
}
}
}
after a while, the fps would be very low, I think there is too many draw calls. Is there any way to solve this problem? Thank you
Comment
Answer by Eric5h5 · Jan 04, 2017 at 10:03 AM
Use the Mesh class to create objects rather than using separate cubes. Do a search for things like "minecraft unity" and you can get lots of info since this has been asked and answered many times.
Follow this Question
Related Questions
Baked Light Maps 2 Answers
Strange static batching behaviour 0 Answers
Draw call increased on duplicated object. But not on others 0 Answers
Share material to reduce draw calls 3 Answers