C# - Renderer.bounds and MeshFilter.mesh.bounds returning different sizes

I’m trying to find the size of an object that also includes its children. I’ve set up the following two functions, the first using Renderer.bounds and the second using MeshFilter.mesh.bounds:

//Find Combined Renderer Bounds
public Bounds FindCombinedRendererBounds (GameObject gameObject) {
	Bounds combinedBounds;
	Renderer startRenderer;
	
	
	var renderers = gameObject.GetComponentsInChildren<Renderer>();
	startRenderer = renderers[0];
	combinedBounds = startRenderer.bounds;
	
	foreach (Renderer renderer in renderers) {
		if (renderer != startRenderer) {
			combinedBounds.Encapsulate (renderer.bounds);
		}
	}

	return combinedBounds;
}
//Find Combined Mesh Bounds
public Bounds FindCombinedMeshBounds (GameObject gameObject) {
	Bounds combinedBounds;
	MeshFilter startMeshFilter;


	var meshFilters = gameObject.GetComponentsInChildren<MeshFilter>();
	startMeshFilter = meshFilters[0];
	combinedBounds = startMeshFilter.mesh.bounds;

	foreach (MeshFilter meshFilter in meshFilters) {
		if (meshFilter != startMeshFilter) {
			combinedBounds.Encapsulate (meshFilter.mesh.bounds);
		}
	}

	return combinedBounds;
}

I’ve then used the code to return the y size of the same object, but have found that both functions return different sizes. I’m confident that the Renderer version is returning the wrong size, but I’m not sure why. My assumption was that both the Renderer and Mesh versions should return the same value if given the same object. As a result I can’t use the Renderer function to return an accurate size for a group of objects.

Any thoughts?

Mesh.bounds:

Thanks for the reply Danuts, I was just about to edit my post actually to address that. One of the parent objects is a different scale, so I imagine that’s what’s causing the issue. Guess I’ll need to find a way for it to test if the scale is different.

I don’t know what you want to do about your scale stuff, but you can simplify a lot of that code.

namespace UnityEngine
{
	using System.Collections.Generic;
	using System.Linq;
	
	public static class BoundsExtensions
	{
		public static Bounds EncapsulatedBounds(this IEnumerable<Renderer> renderers)
		{
			return renderers.Select(renderer => renderer.bounds).Encapsulation();
		}

		public static Bounds EncapsulatedBounds(this IEnumerable<Mesh> meshes)
		{
			return meshes.Select(mesh => mesh.bounds).Encapsulation();
		}

		public static Bounds Encapsulation(this IEnumerable<Bounds> bounds)
		{
			return bounds.Aggregate((encapsulation, next) => 
			{
				encapsulation.Encapsulate(next);
				return encapsulation;
			});
		}
	}
}
2 Likes