Wrap Selected Objects with Box Collider [Boo]

Just thought I’d share some Boo scripts I’ve written now and then, to show how they work. If you like C# or JS better, you can pretty easily port these scripts to your favorite language. I like Boo for the brevity, and the similarity to Python, my usual non-Unity language of choice.

I wanted a simple editor helper script to wrap an object and all its children (recursively) in a single BoxCollider.

def GetChildBounds(obj as GameObject) as Bounds:
    #RECURSIVE
    bounds = Bounds(obj.transform.position, Vector3.zero)
    if obj.renderer:
        bounds = obj.renderer.bounds
    for child as Transform in obj.transform:
        bounds.Encapsulate(GetChildBounds(child.gameObject))
    return bounds

def AutofitBoxCollider(obj as GameObject):
    collider = obj.GetComponent[of BoxCollider]()
    if not collider:
        collider = obj.AddComponent[of BoxCollider]()
    bounds = GetChildBounds(obj)
    collider.center = bounds.center - obj.transform.position
    collider.size = bounds.size

[MenuItem('Helpers/Wrap Selected Objects in Box Colliders')]
def WrapObjectsInBoxColliders():
    for obj in Selection.objects:
        if obj isa GameObject:
            gob = (obj as GameObject)
            AutofitBoxCollider(gob)

Here, I broke the simple operation into three parts. It’s usually a good thing to break up tasks when they have different “concerns” or data types. There is the user’s selection, the collider we’re manipulating, and the bounds calculation for children. A single routine that did all those things could end up quite a bit longer than all three separate tasks (especially if part of the job can be handled with recursion or a coroutine), and it’s harder to follow the logic.

The WrapObjectsInBoxColliders() function is the user interface; it can perform its task on each thing that is selected in the hierarchy.

The AutoFitBoxCollider() function is the routine that deals with the collider itself; it adjusts the existing collider if there is one, or makes a new component.

The GetChildBounds() function calculates the bounds of the current object’s renderer (if it has one), plus all the bounds of all the children. It is recursive; to find the bounds of a child, you want to find the bounds of the child’s children too.

need this script in c#