导航

【Unity】用Graphics.DrawMeshNow在场景中画个三角形

Posted on 2024-01-12 21:14  Caiger  阅读(139)  评论(0编辑  收藏  举报
  • 效果图:

  •  代码:
 1 using System;
 2 using System.Collections;
 3 using System.Collections.Generic;
 4 using UnityEngine;
 5 
 6 public class Draw : MonoBehaviour
 7 {
 8     public Material Mat;
 9     private List<Vector3> vertices;
10     private List<int> triangles;
11     private Mesh mesh;
12 
13     private void Init()
14     {
15         mesh ??= new Mesh();
16         vertices ??= new List<Vector3>();
17         triangles ??= new List<int>();
18 
19     }
20 
21     void OnDrawGizmos()
22     {
23         Init();
24         DrawTriangle();
25 
26     }
27 
28     private void DrawTriangle()
29     {
30         // 一定要有材质,不然mesh看不见
31         if (Mat == null)
32         {
33             return;
34         }
35 
36         vertices.Clear();
37         vertices.Add(Vector3.zero);
38         vertices.Add(new Vector3(0, 0, 1));
39         vertices.Add(new Vector3(1, 0, 0));
40 
41         triangles.Clear();
42         triangles.Add(0);
43         triangles.Add(1);
44         triangles.Add(2);
45 
46         mesh.SetVertices(vertices);
47         mesh.SetTriangles(triangles, 0);
48         mesh.RecalculateNormals();
49 
50         for (int i = 0; i < Mat.passCount; i++)
51         {
52             if (Mat.SetPass(i))
53             {
54                 Graphics.DrawMeshNow(mesh, Matrix4x4.identity);
55             }
56         }
57 
58     }
59 
60 
61 }