I followed a tutorial for Perlin noise. I tried mapping it onto a plane I generated with code, but something about the texture caused the noise to generate like a barcode (straight lines in the z direction) (I think it might be a UV mapping issue, but I can’t figure out where it went wrong). I tried attaching the same two scripts to a normal unity plane and it worked, but when I tried my code-generated one it didn’t work.
Code for the noise function:
public int width = 256;
public int height = 256;
public float scale = 20f;
public float offsetX = 100f;
public float offsetY = 100f;
void OnValidate()
{
GetComponent<Renderer>().sharedMaterial = new Material(Shader.Find("Standard"));
GetComponent<Renderer>().sharedMaterial.mainTexture = null;
mapNoise();
}
Texture2D GenerateTexture()
{
Texture2D noiseTexture = new Texture2D(width, height);
Color[] colors = new Color[width * height];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
colors[y * width + x] = CalculateColor(x, y);
}
}
noiseTexture.SetPixels(colors);
noiseTexture.Apply();
return noiseTexture;
}
Color CalculateColor(int x, int y)
{
float xCoord = (float)x / width * scale + offsetX;
float yCoord = (float)y / height * scale + offsetY;
float sample = Mathf.PerlinNoise(xCoord, yCoord);
return new Color(sample, sample, sample);
}
public void mapNoise()
{
Renderer renderer = GetComponent<Renderer>();
renderer.sharedMaterial.mainTexture = GenerateTexture();
}
Code I used to generate a plane mesh w/ uv mapping:
public class dynamicPlane : MonoBehaviour {
Mesh mesh;
Vector3[] vertices;
int[] triangles;
[Range(1f, 100f)]
public float xScale = 1f;
[Range(1f, 100f)]
public float zScale = 1f;
[Range(2, 256)]
public int resolution = 2;
public bool getTerrainNoise = false;
void OnValidate() {
mesh = new Mesh();
GetComponent<MeshFilter>().sharedMesh = mesh;
GeneratePlane();
}
void GeneratePlane() {
mesh.Clear();
Vector3[] vertices = new Vector3[resolution * resolution];
int[] triangles = new int[(resolution) * (resolution) * 6];
int triIndex = 0;
for (int z = 0; z < resolution; z++) {
for (int x = 0; x < resolution; x++) {
int i = x + z * resolution;
float y = transform.position.y;
Vector3 planePoint = new Vector3(x * xScale / (resolution - 1), y, z * zScale / (resolution - 1));
vertices *= planePoint;*
if (x != resolution - 1 && z != resolution - 1) {
triangles[triIndex] = i;
triangles[triIndex + 1] = resolution + i;
triangles[triIndex + 2] = i + 1;
triangles[triIndex + 3] = resolution + i + 1;
triangles[triIndex + 4] = i + 1;
triangles[triIndex + 5] = resolution + i;
triIndex += 6;
}
}
}
mesh.Clear();
mesh.vertices = vertices;
mesh.triangles = triangles;
Vector3[] verts = vertices;
Vector2[] uvs = new Vector2[verts.Length];
for (int i = 0; i < verts.Length; i++)
{
uvs = new Vector2(verts_.x, verts*.y);
}
mesh.uv = uvs;
mesh.RecalculateNormals();
}
}*_