Why can't Arraymesh generate correctly

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

I want to use Arraymesh to generate geometry for procedural level generation. I want to be able to generate both quads and triangles from simple vertex data. The script that i had written seems to work when dealing with the quadGeneration or triangleGeneration functions alone, but it doesn’t work properly or at all when both are active in the script. What could cause this to happen and how can i fix this? Here’s the code:

extends MeshInstance

export var quadMeshArray = [
    Vector3(0, 0, 0),
    Vector3(1, 0, 0),
    Vector3(1, 0, 1),
    Vector3(0, 0, 1),

    Vector3(1, 0, 0),
    Vector3(2, 0, 0),
    Vector3(2, 0, 1),
    Vector3(1, 0, 1),

    Vector3(-2, 0, 0),
    Vector3(-1, 0, 0),
    Vector3(-1, 0, 1),
    Vector3(-2, 0, 1),

    Vector3(-2, 0, 1),
    Vector3(-1, 0, 1),
    Vector3(-1, 0, 2),
    Vector3(-2, 0, 2),
    ]
export var triangleMeshArray = [
    Vector3(3, 0, 3),
    Vector3(2, 0, 3),
    Vector3(2, 0, 3),
]
var st = SurfaceTool.new()
func _ready():
    st.begin(Mesh.PRIMITIVE_TRIANGLES)
    
    triangleGeneration()
    quadGeneration()
    
    st.generate_normals()
    mesh = st.commit()

func quadGeneration():
    
    var vertexCount = 0
    var indexCount = 0
    
    for num in quadMeshArray.size()/4:
        for i in 4:
            st.add_vertex(quadMeshArray[vertexCount])
            vertexCount += 1
        st.add_index(indexCount)
        st.add_index(indexCount + 1)
        st.add_index(indexCount + 2)
        st.add_index(indexCount + 3)
        st.add_index(indexCount)
        st.add_index(indexCount + 2)
        indexCount += 4
        
func triangleGeneration():
    var vertexCount = 0
    var indexCount = 0
    
    for num in triangleMeshArray.size()/3:
        for i in 3:
            st.add_vertex(triangleMeshArray[vertexCount])
            vertexCount += 1
        st.add_index(indexCount)
        st.add_index(indexCount + 1)
        st.add_index(indexCount + 2)
        indexCount += 3
:bust_in_silhouette: Reply From: Bean_of_all_Beans

Just looking at the code, it seems you don’t define st in either quadGeneration nor triangleGeneration. While you do define it under _ready, it is technically out-of-scope of both the called methods. A quick and easy fix is to have both quadGeneration and triangleGeneration take a single parameter that you would then pass st into from _ready.

For example, you could put func quadGeneration(st): and func triangleGeneration(st) so that you won’t have to change anything else in your code. This should fix your issue.