Instantiating prefabs within the MeshFilter volume of object

Hello all! I would need some help here, since it is hard due to my knowledge to conceive the whole picture of the concept/problem.


I have the above scene, where these green-outlined objects are children of another object and they are basically primitive cubes rotated and scaled. I would like to instantiate these (smaller) blue prefabs at random positions within their volumes . At run time, I find these children objects and by calling the following function (part of the code) for each one, I get their MeshFilter bounds.

function CalcBounds(index : int, go : GameObject){
	var bounds : Bounds = go.GetComponent(MeshFilter).sharedMesh.bounds;
	var center : Vector3 =;
	var extents : Vector3 = bounds.extents;

	v3Center[index] = go.transform.TransformPoint(thisCenter);
	v3Extents[index] = Vector3(extents.x * go.transform.localScale.x,
							extents.y * go.transform.localScale.y,
							extents.z * go.transform.localScale.z); 

From these values I try to instantiate the blue prefabs at offset points around the children’s with this other code in another function:

spawnPoint = Vector3(v3Center[j].x + Random.Range(-v3Extents[j].x, v3Extents[j].x),
					v3Center[j].y + Random.Range(-v3Extents[j].y, v3Extents[j].y),
					v3Center[j].z + Random.Range(-v3Extents[j].z, v3Extents[j].z));

var blueObject : GameObject = Instantiate(prefab, spawnPoint, transform.rotation);

The result, however, is that the blue prefabs are instantiated near the locations I want, but also outside the children objects’ volume. I believe the problem has something to do with the fact that although I take into account the scaling of the children objects with *go.transform.localScale, I don’t do the same with the localRotation. Also the transform.rotation in the Instantiate function refers to the parent object of the green children, on which the script is attached. If it is so, what should I do to implement rotation and at which point of the flow?

Thank you in advance!

While you translate the center to world coordinates, the corners of the bounds will also be in local coordinates and not necessarily axes aligned. Your generation of the spawn point is assuming an axes aligned cube.

The solution is to generate the random point in local coordinates, and then convert the result to world coordinates. Assuming a built-in cube, you can do:

localPosition = Vector3(Random.Range(-.5, .5), Random.Range(-.5, .5), Random.Range(-.5, .5));
spawnPoint = go.transform.TransformPoint(localPosition);

Note this assure the position is inside the cube, not the whole blue cube. You’d have to tighten up the range to assure the whole blue cube is inside.

If you are going to be extending this concept to mesh objects other than cubes, you can use a Random.Range() based on the extents of the mesh.bounds rather than a hard-coded 0.5.