Bounds, Colliders, Instantiated Object

Hello,

I am trying to add a Box Collider to an instantiated GameObject at runtime and scale appropriately. I and am running into issues and am wondering if it’s even possible to do. I am trying to get the local size of the instantiated GameObject and then scale the BoxCollider to match. I have scoured the forums as well as the scripting site and it seems there is no clear answer and a lot of people have had similiar issues. Does anyone know why the code below dill not work? I have added cubes to see where the actual positioning of the placement is. I would like to use BoxColliders sized up so they fit around the instantiated GameObjects but am not opposed to using transparent cubes. The biggest issue is, if I use the Renderer.bounds, I get the world coordinates which is not sufficient because the user can rotate the object, so if they rotate the object, the collider needs to rotate as well. So, I am trying to use the Mesh.bounds as I understand this is the local coordinates. However, when I use the Mesh.bounds, I just get one big cube in front of the instantiated GameObjects. Here is my current code:


//add mesh collider so raycast can collide
GameObject child = GameObject.Find((string)tmpArray[0]);

/*//RENDERER BOUNDS
//bounds variable used for children bounds
Bounds childrenBounds = new Bounds(child.transform.position,Vector3.one);

//get bounds of all renderers in child
Renderer[ ] rendererComponents = child.GetComponentsInChildren ();
foreach (Renderer component in rendererComponents) {
//Debug.Log (component.name);
childrenBounds.Encapsulate(component.bounds);
}*/

//bounds variable used for children bounds
Bounds childrenBounds = new Bounds(child.transform.localPosition,Vector3.one);

//get bounds of all renderers in child
MeshFilter[ ] rendererComponents = child.GetComponentsInChildren();
foreach (MeshFilter component in rendererComponents) {
//Debug.Log (component.name);
component.mesh.RecalculateBounds();
childrenBounds.Encapsulate(component.mesh.bounds);
}

//create transparent cube to capture raycast hit, name it the same as the parent
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.name = child.name;
cube.transform.parent = child.transform;
cube.transform.position = childrenBounds.center;
cube.transform.localScale = childrenBounds.size;
//cube.renderer.material.shader = Shader.Find(“Transparent/Diffuse”);
Color clTransparent = cube.renderer.material.color;
clTransparent.a = 0.0f;
cube.renderer.material.color = clTransparent; //make the cube transparent

Any help is greatly appreciated.

Sam

Use forum code tag.
This horrible thing nobody reads.