Create a mesh, create a material at runtime in Godot V3.0

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

The source is here: GitHub - imekon/godot-unofficial-demo-projects-v3: Unofficial demo projects for V3, in the project mesh.

The main.gd file has this:

extends Spatial

onready var meshInstance = $Mesh

var angle = 0

func _ready():
    var material = SpatialMaterial.new()
    material.albedo_color = Color(1.0, 0.0, 0.0)
    createMesh(10, material)

func createMesh(size, material):
    var surfaceTool = SurfaceTool.new()
    surfaceTool.begin(Mesh.PRIMITIVE_TRIANGLES)

    surfaceTool.add_normal(Vector3(    0,     0,  1))

    surfaceTool.add_vertex(Vector3(-size, -size,  0))
    surfaceTool.add_vertex(Vector3( size,  size,  0))
    surfaceTool.add_vertex(Vector3( size, -size,  0))
    surfaceTool.add_vertex(Vector3(-size, -size,  0))
    surfaceTool.add_vertex(Vector3(-size,  size,  0))
    surfaceTool.add_vertex(Vector3( size,  size,  0))

    var mesh = surfaceTool.commit()
    meshInstance.mesh = mesh
    meshInstance.set_surface_material(0, material)

func _process(delta):
    angle += delta * 30
    meshInstance.rotation_degrees = Vector3(0, 0, angle)

It creates a white surface not red, and I’m not clear why.

I can see red rectangle is rotating with your test code.
I’m testing with custom build v3.1.dev.dd4e593
would you try it with 3.0.1-official?

volzhs | 2018-02-27 19:53

:bust_in_silhouette: Reply From: D3m0n92
material.albedo_color = Color(1.0, 0.0, 0.0, **1.0**)
meshInstance.set_material_override(material)

Miss alpha channel. Test it

:bust_in_silhouette: Reply From: phatsen

I had the same problem until now - This works for me (Godot 3.0.2-stable)

var material = SpatialMaterial.new()
material.albedo_color = Color(0.8, 0.0, 0.0)
var st = SurfaceTool.new()
st.begin(Mesh.PRIMITIVE_TRIANGLES)
st.set_material(material)
st.add_vertex(Vector3(5, 0, 0))
st.add_vertex(Vector3(0, 5, 0))
st.add_vertex(Vector3(5, 5, 0))
st.generate_normals()
var mesh = Mesh.new()
st.commit(mesh)
var mesh_inst = MeshInstance.new()
mesh_inst.mesh = mesh
add_child(mesh_inst)

Mind, that you FIRST have to state SurfaceTool.begin(), and THEN SurfaceTool.set_material()
In this tutorial, they switched the lines (maybe worked in previous versions?)