I have a 2d sidescrolling game with a lot of different sized scenes. I want the camera to move along the scene until the end, without hardcoding the size of the scene.
I can’t find scene.size in the docs How do I find out the maximum bounding box of an entire scene?
There’s no such concept built in to Unity. You’ll have to make up your own. You could do it with an invisible box or just two empty objects that act as min and max corners.
1 Like
There’s no end to a scene nor any limitations on scene size. If you want the camera to stop at the edge of something, you have to define that limitation, Unity doesn’t arbitrarily limit things like camera position.
2 Likes
OK, thanks! I am now writing a loop that goes through all game objects and checks the minimum and maximum positions, so I know the size of the actual level. I don’t want to use an invisible box in my specific use case (the scene has to be easily alterable without needing to think about resizing the invisible box)
1 Like
I’d just put a trigger collider at the “end” of the scene. Camera hits it, means it is at the end.
1 Like
That works, but the scene contents may change, so then the trigger collider will constantly have to be updated too, and I still have to calculate how far to the right the trigger collider should be moved.
I coded this function which creates a Bounds object for the scene.
public Bounds getSceneSize() {
float max_x = -Mathf.Infinity;
float min_x = Mathf.Infinity;
SpriteRenderer[] allSprites = FindObjectsOfType<SpriteRenderer>();
foreach (SpriteRenderer sprite in allSprites) {
float right_x = sprite.bounds.max.x;
float left_x = sprite.bounds.min.x;
if (right_x > max_x) {
max_x = right_x;
}
if(left_x < min_x){
min_x = left_x;
}
}
Bounds b = new Bounds();
b.min = new Vector3(min_x, 0, 0);
b.max = new Vector3(max_x, 0, 0);
return b;
}
1 Like