How can I cull my prefabs that aren't inside the 2D Camera View in Unity

279 Views Asked by At

I'm working on replicating the game "Deepworld". I setup world gen using array maps and some special logic. I'm creating hundreds of objects in seconds. This destroys performance.

Even hitting the play button takes a while, and it's pretty hard to "exit" play mode, as it's basically 1 fps.

How should I go about culling everything not in the camera view. I don't understand any logic around the camera's view within C#.

If I knew more about how I could access the actual location and size of the camera's view, I could probably do something along these lines.

... {
    for (int y = 0; y < height; y++) {
        Vector3 pos = new Vector3(-width / 2 + x + 0.5f, objectHolder.transform.position.y, -height / 2 + y + 0.5f);
    
        // Imaginary If Conditions Ahead

        if (pos.x <= CameraViewMaxX && pos.x >= CameraViewMinX && pos.y <= CameraViewMaxY && pos.y >= CameraViewMinY) {
            Gizmos.color = (map[x, y] == 1)? Color.white : Color.clear;
            Gizmos.DrawCube(pos, Vector3.one);
            if (map[x, y] == 0) {
                Instantiate(block, pos, objectHolder.transform.rotation);
            }
        }

        // Back to Normal
    }
}

I don't know what direction to go in, and I don't know how to physically implement this into my game.

I know that I'm only supposed to load blocks in the view, like Terraria or Deepworld. That's the only reason those games run smoothly. It's because of the culling.

enter image description here

0

There are 0 best solutions below