程序网格减慢了统一场景

时间:2014-04-08 02:59:00

标签: c# unity3d mesh

我在Unity3d中创建一个非常简单的游戏,我需要创建多个网格物体。我创建的代码非常简单,但在同时拥有8个以上的网格后,同步性能大大降低到几个fps(~8 fps)。我创建的Mesh只是一个简单的方块,所以我真的不知道问题出在哪里,这是我的代码:

using UnityEngine;
using System.Collections;

public class TetraGenerator : MonoBehaviour {
    public int slices;
    public GameObject forceSource;
    void OnMouseDown(){
        var arcLength = Mathf.PI / slices;
        var distance = 10;
        var height = 1;
        var origin = Random.Range(-slices,slices);

        Vector3[] vertices = new Vector3[4];
        vertices [0] = new Vector3 (Mathf.Cos(origin*arcLength),Mathf.Sin(origin*arcLength));
        vertices [1] = new Vector3 (Mathf.Cos(origin*arcLength),Mathf.Sin(origin*arcLength));
        vertices [2] = new Vector3 (Mathf.Cos((origin+1)*arcLength),Mathf.Sin((origin+1)*arcLength));
        vertices [3] = new Vector3 (Mathf.Cos((origin+1)*arcLength),Mathf.Sin((origin+1)*arcLength));

        vertices [0] *= distance;
        vertices [1] *= (distance+height);
        vertices [2] *= (distance+height);
        vertices [3] *= distance;

        Vector3 frameRef = new Vector3(Mathf.Cos(origin*arcLength+(arcLength/2)),Mathf.Sin(origin*arcLength+(arcLength/2)));
        frameRef *= distance;

        vertices [0] -= frameRef;
        vertices [1] -= frameRef;
        vertices [2] -= frameRef;
        vertices [3] -= frameRef;

        int[] triangles = new int[]{0,1,2,2,3,0};

        Mesh mesh = new Mesh ();
        mesh.vertices = vertices;
        mesh.triangles = triangles;

        GameObject tile = new GameObject("tile",typeof(MeshFilter),typeof(MeshRenderer));
        tile.transform.position = frameRef;

        MeshFilter meshFilter = tile.GetComponent<MeshFilter> ();
        meshFilter.mesh = mesh;

    }
}

1 个答案:

答案 0 :(得分:1)

您的问题是您没有设置材料,或者您没有提供材料所需的所有材料,如紫外线坐标或顶点颜色。我不确定它是否是Debug.Log中的错误消息,或者着色器本身是否导致低帧率,但测试它可以使用:

// enter this at the top and set the material in the inspector
public Material mat;

[...]

// enter this at the bottom
MeshRenderer meshRenderer = tile.GetComponent<MeshRenderer>();
meshRenderer.material = mat;

作为材料,您可以创建一个新的并使用带有此代码的着色器:

Shader "SimpleShader"
{
    SubShader
    {
        Pass
        {
            CGPROGRAM

            #pragma vertex vert
            #pragma fragment frag

            struct vertexInput
            {
                float4 pos : POSITION;
            };

            struct vertexOutput
            {
                float4 pos : SV_POSITION;
                float4 col : COLOR0;
            };

            vertexOutput vert(vertexInput input)
            {
                vertexOutput output;

                output.pos = mul(UNITY_MATRIX_MVP, input.pos);
                output.col = float4(1, 0, 0, 1);

                return output;
            }

            float4 frag(vertexOutput input) : COLOR
            {
                return input.col;
            }

            ENDCG
        }
    }
}