Skip to content

Instantly share code, notes, and snippets.

@ArieLeo
Created July 26, 2024 09:20
Show Gist options
  • Save ArieLeo/ff2c6768b73c969b3c9d0ace7e254dc8 to your computer and use it in GitHub Desktop.
Save ArieLeo/ff2c6768b73c969b3c9d0ace7e254dc8 to your computer and use it in GitHub Desktop.
Autofit Box collider to Mesh Renderer Bounds, usefull when you are trying to adjust box collider on multiple objects at once
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
public static class AutoFitBoxCollider
{
[MenuItem("Tools/Autofit BoxCollider")]
private static void AutoFitBoxCollider()
{
var gos = Selection.gameObjects;
if (PrefabStageUtility.GetCurrentPrefabStage() != null)
{
foreach (var go in gos)
{
if (!go.TryGetComponent(out MeshRenderer mr))
{
continue;
}
if (!go.TryGetComponent(out BoxCollider bc))
{
continue;
}
var bound = mr.localBounds;
bc.size = bound.size;
bc.center = bound.center;
EditorUtility.SetDirty(go.gameObject);
}
}
else
{
foreach (var go in gos)
{
if (!go.TryGetComponent(out MeshRenderer mr))
{
continue;
}
if (!go.TryGetComponent(out BoxCollider bc))
{
continue;
}
var bound = mr.localBounds;
bc.size = bound.size;
bc.center = bound.center;
EditorUtility.SetDirty(go.gameObject);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment