How to "Unwrap UV2 for Lightmap/AO" from GDscript?

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

There’s already someone else who asked a question about this but no one has answered so I’m just gonna link it here.

:bust_in_silhouette: Reply From: Dadaskis

Hey pal. I know it’s a long time since you posted this question, but i’m running into this problem during these days so i’m going to leave this answer right here:

extends MeshInstance

export(float) var lightmap_texel_size = 0.4

func process_uv2():
	var old_mesh = mesh as Mesh
	mesh = ArrayMesh.new()

	for surface_id in range(old_mesh.get_surface_count()):
		mesh.add_surface_from_arrays(
			Mesh.PRIMITIVE_TRIANGLES, 
			old_mesh.surface_get_arrays(surface_id)
		)
		var old_mat = old_mesh.surface_get_material(surface_id)
		mesh.surface_set_material(surface_id, old_mat)

	mesh.lightmap_unwrap(global_transform, lightmap_texel_size)
	use_in_baked_light = true

func _ready():
	process_uv2()

I personally use it as a part of my tool scripts