unity3d 为什么我在Unity中程序生成的网格没有任何阴影?

pokxtpni  于 2023-03-23  发布在  其他
关注(0)|答案(1)|浏览(235)

我用C#生成了一个网格,它工作了,但是没有阴影。我希望阴影像Unity中内置的地形一样工作,但是它没有。
我有一个方向光源指向上面的网格,网格渲染器设置为投射阴影和接收阴影= ON。这可能与着色器有关吗?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(MeshFilter))]
public class ChunkGeneration : MonoBehaviour
{
    Mesh mesh;

    Vector3[] vertices;
    int[] triangles;

    public int size = 100;
    // Start is called before the first frame update
    void Start()
    {
        //Create a new mesh 
        mesh = new Mesh();
        CreateShape();
        UpdateMesh();
        
        GetComponent<MeshFilter>().mesh = mesh;
        GetComponent<MeshCollider>().sharedMesh = mesh;

        

    }

    // Update is called once per frame
    void Update()
    {
        
    }

    void CreateShape() {
        //Create vertices for mesh
        vertices = new Vector3[(size + 1 ) * (size + 1)];

        for (int i = 0, z = 0; z < size + 1; z++) {
            for (int x = 0; x < size + 1; x++) {

                float y = Mathf.PerlinNoise(x * .3f, z * .3f);
                vertices[i] = new Vector3(x, y, z); //WHY WHEN Z IN Y_VALUE IT WORK???
                i++;
            }
        }

        //Create triangles for mesh
        triangles = new int[size * size * 6];

        int vert = 0;
        int tris = 0;

        for (int z = 0; z < size; z++) {
            for (int x = 0; x < size; x++) 
            {
                triangles[tris + 0] = vert + 0;
                triangles[tris + 1] = vert + size + 1;
                triangles[tris + 2] = vert + 1;
                triangles[tris + 3] = vert + 1;
                triangles[tris + 4] = vert + size + 1;
                triangles[tris + 5] = vert + size + 2;

                vert++;
                tris += 6;
            }
            vert++;
        }

    }

    void UpdateMesh() {
        //Reset and update mesh
        mesh.Clear();

        mesh.vertices = vertices;
        mesh.triangles = triangles;
    }
}
yqkkidmi

yqkkidmi1#

这是因为你还没有计算Normal,所以MeshRenderer还没有识别出Face的主方向是哪一面,以及如何计算光线,加上下面这行就解决了。

void UpdateMesh() {
    //Reset and update mesh
    mesh.Clear();

    mesh.vertices = vertices;
    mesh.triangles = triangles;
    
    mesh.RecalculateNormals(); // You need to calculate Normals..
}

相关问题