- Home /
custom foliage placement - need tips to increase performance
Hi,
i wrote a script which renders some foliage on a mesh terrain. The problem is, it drops the framerate from about 260 down to 90. I really dont like that..
I'm looking for ways to improve it or maybe write a new and better one.
I hope the following code can explain what it does because if i put that in words, it would be even longer:
(in short: Raycast from a grid around the player down to ground, get pixel, if pixel.green>0.5 draw a mesh with color from that pixel)
void DrawFoliage () {
if (draw == true) {
Collider[] cols = Physics.OverlapSphere(transform.position, radius, groundLayer);
if (cols.Length == 0) {
return;
}
foreach( Collider col in cols) {
if (col.renderer == null || col.renderer.material == null) {
return;
}
FoliageHolder fol = col.GetComponent<FoliageHolder>();
Texture2D tex = col.renderer.material.GetTexture("_MixTex") as Texture2D;
float strength = col.renderer.material.GetFloat("_LightMix");
if (tex != null) {
for (int a=0;a<radius;a++) {
for (int b=0;b<radius;b++) {
Vector3 gpoint = transform.position+new Vector3((-radius/2)+b, 0, (-radius/2)+a);
if (Vector3.Distance(gpoint, transform.position)<radius/2) {
gpoint = new Vector3(Mathf.Round(gpoint.x),gpoint.y, Mathf.Round(gpoint.z));
if (Physics.Raycast(gpoint+Vector3.up*(radius/2),Vector3.down, out hit, radius*2, groundLayer)) {
Color fcol = tex.GetPixel(Mathf.RoundToInt(hit.textureCoord.x*tex.width), Mathf.RoundToInt(hit.textureCoord.y*tex.height));
Debug.DrawRay(gpoint+Vector3.up*(radius/2), Vector3.down*(radius*2), fcol);
if (fol != null && fol.foliageMesh != null) {
if (fcol.g>0.5f) {
MaterialPropertyBlock propblock = new MaterialPropertyBlock();
propblock.AddColor("_Emission", new Color(fcol.r*strength/2, fcol.g*strength/2, fcol.b*strength/2, 1.0f));
Graphics.DrawMesh(fol.foliageMesh, hit.point, Quaternion.FromToRotation (transform.up, hit.normal), fol.foliageMaterial, 0,null,0,propblock);
}
}
} else {
Debug.DrawRay(gpoint+Vector3.up*(radius/2), Vector3.down*(radius*2), Color.red);
}
}
}
}
}
}
}
}
Thank you.
hm, ok. i already fixed everything, it now performs very well. Another question that i stumbled upon: how do i scale a mesh drawn with Graphics.Draw$$anonymous$$esh()?
i guess i have to write a special shader for that and input a matrix through the $$anonymous$$aterialBlockProperty?