程序网格会减慢统一场景的速度
本文关键字:一场 速度 网格 程序 | 更新日期: 2023-09-27 17:57:10
我在Unity3d中创建了一个非常简单的游戏,我需要在其中创建多个网格体。我创建的代码非常简单,但是在同时拥有 8 个以上的网格后,对等性能大大降低到只有几 fps (~8 fps)。我创建的网格只是一个简单的正方形,所以我真的不知道问题出在哪里,这是我的代码:
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;
}
}
您的问题是您没有设置材质,或者您没有提供材质所需的一切,例如 UV 坐标或顶点颜色。我不确定是 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
}
}
}