As the title suggests, I'm trying to create a mesh at runtime through code (GDScript). However I'm not having much luck.
I'm starting with a simple quad for now, with the intention to move on to more interesting things once I understand how this works. The code looks like this:
extends StaticBody
func make_quad(): #mesh
var array = Array()
array.push_back(Vector3(0,0,0))
array.push_back(Vector3(0,1,0))
array.push_back(Vector3(1,1,0))
array.push_back(Vector3(1,0,0))
print(array.size()) #expected: 4, result: 4
var mesh = Mesh.new()
mesh.add_surface(Mesh.PRIMITIVE_TRIANGLE_STRIP, array)
print(mesh.surface_get_array_len(0)) #expected: 4, result: -1
return mesh
func _init():
var mesh = make_quad()
var meshinst = MeshInstance.new()
meshinst.set_mesh(mesh)
add_child(meshinst)
print("surface count ", mesh.get_surface_count()) #expected: 1, result: 0
print("format ", mesh.surface_get_format(0)) #expected: ???, result: 0
print("primitive ", mesh.surface_get_primitive_type(0)) #expected: 5, result: 1
Then in the root Spatial node's _ready()
function I load the script file, instantiate an object and add_child()
it to the scene.
The docs aren't clear on what format the array parameter to add_surface()
takes; I've tried an Array
of Vector3
s as in the above code, a Vector3Array
and an Array
of [x, y, z]
triplets. All give the same result.
The code appears to be quietly failing on the add_surface()
function, as the debugger shows an error at that line and also on the subsequent surface_*
calls, but it doesn't give any details of the error which makes it hard to debug!
The doc page for Mesh
talks a lot about "format" and the Mesh
class contains a number of flags related to format, but there is no way to pass a format parameter so I don't see how to set this.