How can I add collision to all members of a MeshLibrary?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ettolrach

I am following the documentation on GridMaps and am trying to add collision to the models. I imported these models from an asset pack and they 300 odd models in this library.

Is there a way to either add collision to all of them without having to individually select each one, then go to the “Mesh” button and selecting “Create Trimesh Static Body”? If not, is there a way of adding collision to these tiles as you add them to a scene with GridMaps?

:bust_in_silhouette: Reply From: Tallawk

I’ve been working on automating a few things like this myself. Before converting the scene to a MeshLibrary, try this: (sorry if the formatting is messed up, tabs got lost, I tried)

tool
extends Spatial

# ToolStaticBodyMaker.gd
# Takes a scene of imported MeshInstances and creates StaticBodys for them
# Also builds CollisionShape and Shape for each.
# To use:
# First save scene as a .tscn file, and clear inheritance!
# Attach this script to a scene of imported meshes
# Set IS_CONVEX to false to build concave Shape if desired.
# See engine docs for CLEAN & SIMPLIFY (if you can find them?)
# Save scene; close/reload; it will run, and do it's thing.
# Detach this script and save your scene; carry on!

const IS_CONVEX = true
const CLEAN = true
const SIMPLIFY = false

func _ready():
_work()

func _work():
var root: Spatial = self
for mi in root.get_children():
if mi.is_class(“MeshInstance”):
print("Found MeshInstance ", mi)
var meshInst: MeshInstance = mi # Just a recast
var statBod: StaticBody = StaticBody.new()
# Attach the new StaticBody
root.add_child(statBod)
statBod.set_owner(root)
# Move the MeshInst to the StaticBody
root.remove_child(meshInst)
statBod.add_child(meshInst)
meshInst.set_owner(root)
# Preserve the MeshInst name in the new StaticBody
statBod.set_name(meshInst.get_name())
# Make and attach CollisionShape
var collShp: CollisionShape = CollisionShape.new()
statBod.add_child(collShp)
collShp.set_owner(root) # WHY NOT STATBOD WORK??? WHY???
# Make and fill out the Shape
var mesh: Mesh = meshInst.get_mesh() # Basically extract/cast
if IS_CONVEX:
var shape = ConvexPolygonShape.new()
shape = mesh.create_convex_shape(CLEAN, SIMPLIFY)
collShp.set_shape(shape)
else: # Is concave:
var shape = ConcavePolygonShape.new()
shape = mesh.create_trimesh_shape()
collShp.set_shape(shape)