Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Generates a box collider for the bounds of a brush or a convex mesh collider using the source polygons of a brush, also copies any referenced components to the built object. Note: you should disable collision on the source brush so that it isn't built into two separate colliders
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Sabresaurus.SabreCSG;
using UnityEditor;
public class BrushToCollider : MonoBehaviour, IPostBuildListener
bool generateCollider = true;
bool isTrigger;
bool preferBoxCollider = true;
List<Component> componentsToCopy = new List<Component>();
public void OnBuildFinished(Transform meshGroupTransform)
// Create a new object to hold the collider/components
GameObject newObject = new GameObject(;
newObject.transform.position = this.transform.position;
newObject.transform.rotation = this.transform.rotation;
newObject.transform.localScale = this.transform.localScale;
// If the user wants a collider generate one with the bounds of the brush
Brush brush = GetComponent<Brush>();
Bounds localBounds = brush.GetBounds();
BoxCollider boxCollider = newObject.AddComponent<BoxCollider>();
boxCollider.size = localBounds.extents;
boxCollider.isTrigger = isTrigger;
Polygon[] polygons = brush.GetPolygons();
Mesh mesh = new Mesh();
List<int> polygonIndices = new List<int>();
// Convert the source polygons into a Unity mesh
BrushFactory.GenerateMeshFromPolygons(polygons, ref mesh, out polygonIndices);
// Create a mesh collider and assign the mesh to it
MeshCollider meshCollider = newObject.AddComponent<MeshCollider>();
meshCollider.sharedMesh = mesh;
meshCollider.convex = true; // Brushes are convex so mesh collider might as well be too
meshCollider.isTrigger = isTrigger;
// Copy all referenced components to the new object
for (int i = 0; i < componentsToCopy.Count; i++)
if(componentsToCopy[i] != null)
Component newComponent = newObject.AddComponent(componentsToCopy[i].GetType());
EditorUtility.CopySerialized(componentsToCopy[i], newComponent);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment