Objects spawning half out of camera bounds

Studying Unity, and I had a question. Preamble: in the scene, in a random place, objects are spawning, but some of them appear in half, one part in the camera, the second outside it. (Below is a screenshot)

Random location in the code is indicated as follows:

float spawnY = Random.Range(Camera.main.ScreenToWorldPoint(new Vector2(0, 0)).y, Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height)).y);

float spawnX = Random.Range(Camera.main.ScreenToWorldPoint(new Vector2(0, 0)).x, Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0)).x);

Vector2 spawnPosition = new Vector2(spawnX, spawnY);

GameObject instance = Instantiate(ballPrefab, spawnPosition, Quaternion.identity);

Actually the question is how to make spawning of objects only within the camera and as full object?

P.S. And one more question, is there an option to create a spawn, slightly smaller than the camera, inside the camera and spawn objects in it?

The easiest thing to do is to add a little buffer in from the edges of your screen that can account for the size of the object. This gives you a “safe area” in which you can spawn your object without it overflowing the edges.

float buffer = 50f;  // adjust this based on the size of your objects
Vector3 worldMin = Camera.main.ScreenToWorldPoint(new Vector2(buffer, buffer));
Vector3 worldMax = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width - buffer, Screen.height - buffer));
Vector2 spawnPosition = new Vector2(
   Random.Range(worldMin.x, worldMax.x),
   Random.Range(worldMin.y, worldMax.y));
1 Like

Thank you, it helped a lot. :slight_smile: