Hi,
today i ran into the following problem:
I need to add a (Box)Collider to a GameObject loaded from an AssetBundle. Since it is a complex geometry, i don’t want to add colliders to all children of the root node, but rather just add a collider to the root node and grow it to the size of the full geometry.
From what i read so far all i would have to do is call collider.bounds.encapsulate on all the children of the root node. However when i do that, nothing at all changes about the collider, no matter what i try.
In the code below i made a simplified example of what i mean (instead of loading a geometry i just create 2 primitives) and in the comments you can see the Debug.Log result.
As you can see no matter what i try the bounds of the default boxCollider of my cube primitive stay the same.
So my question is what am i doing wrong??
public class test : MonoBehaviour
{
void Start()
{
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = new Vector3(0, 0, 0);
var sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
Destroy(sphere.GetComponent<SphereCollider>());
//I intentionally remove the collider, since i want to grow
//the cubes collider to include the sphere
sphere.transform.SetParent(cube.transform);
sphere.transform.localPosition = new Vector3(2, 0, 0);
cube.GetComponent<BoxCollider>()
.bounds
.Encapsulate(sphere.GetComponent<Renderer>().bounds);
Debug.Log(cube.GetComponent<BoxCollider>().bounds);
//Result: Center: (0.0, 0.0, 0.0), Extents: (0.5, 0.5, 0.5)
cube.GetComponent<BoxCollider>()
.bounds
.Encapsulate(new Bounds(Vector3.zero, new Vector3(100, 100, 100)));
Debug.Log(cube.GetComponent<BoxCollider>().bounds);
//Result: Center: (0.0, 0.0, 0.0), Extents: (0.5, 0.5, 0.5)
cube.GetComponent<BoxCollider>().bounds.Expand(500);
Debug.Log(cube.GetComponent<BoxCollider>().bounds);
//Result: Center: (0.0, 0.0, 0.0), Extents: (0.5, 0.5, 0.5)
}
}