一、创建空游戏对象
二、创建绘制脚本,并附给新建游戏对象
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
//记录顶点数组
private Vector3[] vertices;
//三角形索引
private int[] triangles;
//记录顶点数
private int count;
private Mesh mesh;
private List<Vector3> list;
// Start is called before the first frame update
void Start()
{
//添加MeshFilter
gameObject.AddComponent<MeshFilter>();
//添加MeshRenderer
gameObject.AddComponent<MeshRenderer>();
//new一个链表
list = new List<Vector3>();
//获得Mesh
mesh = GetComponent<MeshFilter>().mesh;
//修改Material的颜色
GetComponent<MeshRenderer>().material.color = Color.green;
//选择材质的shader
// GetComponent<MeshRenderer>().material.shader = Shander.Find("Transparent/Diffuse");
//清空所有点用于初始化
mesh.Clear();
}
// Update is called once per frame
void Update()
{
//点击鼠标左键
if (Input.GetMouseButton(0))
{
//顶点数+1
count++;
//将鼠标点击的屏幕坐标转换为世界坐标,添加到list链表中
list.Add(Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0.8f)));
}
//如果顶点数>=3 开始渲染
if(count >= 3)
{
//初始化顶点数组
vertices = new Vector3[count];
//将list坐标赋值给顶点坐标数组
for(int i = 0; i < count; i++)
{
vertices[i] = list[i];
}
//三角形网格数
int trangle_count = count - 2;
//三角形索引
triangles = new int[3 * trangle_count];
for(int i =0;i< trangle_count; i++)
{
triangles[3 * i] = 0;
triangles[3 * i + 1] = i + 2;
triangles[3 * i + 2] = i + 1;
}
//设置顶点坐标
mesh.vertices = vertices;
mesh.triangles = triangles;
}
}
}
效果如下:
|