68 lines
2.6 KiB
C#
68 lines
2.6 KiB
C#
using UnityEngine;
|
|
|
|
namespace AmazingAssets.TerrainToMesh.Example
|
|
{
|
|
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
|
|
public class ExportGrass : MonoBehaviour
|
|
{
|
|
public TerrainData terrainData;
|
|
|
|
public int vertexCountHorizontal = 100;
|
|
|
|
public int vertexCountVertical = 100;
|
|
|
|
private void Start()
|
|
{
|
|
if (terrainData == null)
|
|
{
|
|
return;
|
|
}
|
|
Mesh sharedMesh = terrainData.TerrainToMesh().ExportMesh(vertexCountHorizontal, vertexCountVertical, Normal.CalculateFromMesh);
|
|
GetComponent<MeshFilter>().sharedMesh = sharedMesh;
|
|
Material sharedMaterial = new Material(Shader.Find("Standard"));
|
|
GetComponent<Renderer>().sharedMaterial = sharedMaterial;
|
|
DetailPrototypesData[] array = terrainData.TerrainToMesh().ExportGrassData(vertexCountHorizontal, vertexCountVertical, 1, 1, 8, 1f);
|
|
Mesh sharedMesh2 = Utilities.CreateGrassMesh(1);
|
|
Shader shader = Shader.Find(Constants.shaderGrass);
|
|
string materailPropMainTex = Utilities.GetMaterailPropMainTex();
|
|
for (int i = 0; i < array.Length; i++)
|
|
{
|
|
GameObject gameObject = new GameObject("Grass");
|
|
gameObject.transform.SetParent(base.gameObject.transform, worldPositionStays: false);
|
|
Material material = new Material(shader);
|
|
material.SetTexture(materailPropMainTex, array[i].detailPrototype.prototypeTexture);
|
|
for (int j = 0; j < array[i].position.Count; j++)
|
|
{
|
|
GameObject obj = new GameObject("Grass");
|
|
obj.AddComponent<MeshFilter>().sharedMesh = sharedMesh2;
|
|
obj.AddComponent<MeshRenderer>().sharedMaterial = material;
|
|
obj.transform.SetParent(gameObject.transform, worldPositionStays: true);
|
|
obj.transform.localPosition = array[i].position[j];
|
|
obj.transform.localRotation = Quaternion.Euler(0f, Random.value * 360f, 0f);
|
|
obj.transform.localScale = array[i].scale[j];
|
|
}
|
|
foreach (Mesh item in Utilities.CombineGameObjects(gameObject, material, "Grass", array[i].detailPrototype.prototypeTexture.name))
|
|
{
|
|
BakeHealthyAndDryColorsInsideVertexColor(item, array[i].detailPrototype);
|
|
}
|
|
}
|
|
}
|
|
|
|
private void BakeHealthyAndDryColorsInsideVertexColor(Mesh mesh, DetailPrototype detailPrototype)
|
|
{
|
|
Vector3[] vertices = mesh.vertices;
|
|
Color[] colors = mesh.colors;
|
|
Color healthyColor = detailPrototype.healthyColor;
|
|
healthyColor.a = 1f;
|
|
Color dryColor = detailPrototype.dryColor;
|
|
dryColor.a = 1f;
|
|
for (int i = 0; i < vertices.Length; i++)
|
|
{
|
|
float t = Mathf.PerlinNoise(vertices[i].x * detailPrototype.noiseSpread, vertices[i].z * detailPrototype.noiseSpread);
|
|
colors[i] *= Color.Lerp(dryColor, healthyColor, t);
|
|
}
|
|
mesh.colors = colors;
|
|
}
|
|
}
|
|
}
|