尝试使用脚本实时更新网格的顶点位置时Unity游戏引擎崩溃

时间:2015-04-26 02:50:59

标签: c# unity3d scripting monodevelop mesh

所以在统一中,我创建了一个成功生成由三角形组成的平面网格的脚本。该平面具有400个顶点(20×20网格),其中361个正方形由2个三角形组成,每个三角形包括3个顶点(2166个索引)。如前所述,顶点,索引和法线在start()函数中设置,顶点被加载到称为顶点的vector3数组中,索引被加载到单个浮点数组中,法线被加载到vector3数组中。然后将它们分配给Start()函数中的网格(表示平面),如下所示:

public static void main(String eth[]) {
    int a = readInt();
    int b = readInt();
    int answer = (a + b);
    System.out.println(answer);
}
private static int readInt() {
    System.out.println("Write An Integer");
    Scanner input = null;
    while(!(input = new Scanner(System.in)).hasNextInt()){
        System.out.println("Play By The Rules, Write An Integer");
    }
    return input.nextInt();
}

在update()函数中,调用一个函数来计算平面网格中每个顶点的新位置(400):

    mesh.vertices = vertices;
    mesh.triangles = triangles;
    mesh.normals = normals;

updateMesh函数如下所示:

void Update () 
{
    updateMesh ();
    mesh.vertices = vertices;
}

更新新顶点后,索引和法线保持不变,但必须将新计算的顶点位置加载到网格对象上。这也可以在Update()函数中尝试,如上所示。

然而,一旦按下播放按钮,发动机就会崩溃,我不知道为什么 - 重新计算功能是否可能在统一渲染之前完成其循环? (我已经减少了网格中顶点的数量,因为当网格有10000个顶点(100x100网格)时会出现同样的问题)。或者是因为我在Update()函数中没有正确执行某些操作?

2 个答案:

答案 0 :(得分:3)

我认为这可能是该行的错字

for (float i = 0f; i<1f; i=+0.05f) {

它应该是+ = not = +。

它可能会陷入无限循环,因为我永远不会增加。

答案 1 :(得分:0)

我只想指出,使用整数迭代有效的2D数组并完全使用整数数学计算最终的数组索引会更好。例如

如果您依赖浮点数学,则可能会生成类似19.99的索引。然后将四舍五入以索引数组。不理想!希望这可以帮助。

    static int meshWidth = 20;
    static int meshHeight = 20;

    void updateMesh()
    {
        for (int i = 0; i< meshHeight; i++) {
            for (int j = 0; j < meshWidth; j++)
            {
                int pos = i * meshWidth + j;

                // Also change updatePt func to receive two ints...
                vertices[pos] = updatePt(j, i); 
            }
        }
    }