主要思路 :通过鼠标点击屏幕 获得鼠标的位置 并生成 LineRenderer 组件 然后通过list 来储存LineRenderer的位置信息。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UIElements;
public class NewBehaviourScript : MonoBehaviour
{
public GameObject slider;
private LineRenderer line;
private int linepoint;
private int lineindex;
private Vector3 mouspos;
public Material mat;
private Color color;
public bool abc=false;
private GameObject qc;
List<LineRenderer> wt = new List<LineRenderer>();
private GameObject green;
private GameObject tuic;
// Start is called before the first frame update
void Start()
{
color = Color.red;
qc = GameObject.Find("qc");
qc.SetActive(false);
green =GameObject.Find("green");
green.SetActive(false);
tuic = GameObject.Find("tuic");
tuic.SetActive(false);
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject() && abc==true )//鼠标按下一次并且不是在UI上
{
InitLine();
}
if (Input.GetMouseButton(0) && line != null && !EventSystem.current.IsPointerOverGameObject() && abc == true )//鼠标按下不松并且不是在UI上
{
Drawing();
}
}
public void InitLine()
{
GameObject go = new GameObject();
go.name = "LineRenderer";
line = go.AddComponent<LineRenderer>();
line.material.color = color;
line.startWidth = 0.01f;
line.endWidth = 0.01f;
linepoint = 0;
lineindex = 0;
wt.Add(line);
}
public void Drawing()
{
//获取鼠标位置,给一个深度使摄像机能够看到
mouspos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.forward.magnitude * 1));
linepoint++;
line.positionCount = linepoint;//连接LineRenderer的位置个数
if (lineindex < linepoint)
{
lineindex++;
line.SetPosition(lineindex - 1, mouspos);
}
}
public void hb_button()
{
abc = true;
qc.SetActive(true);
green.SetActive(true);
tuic.SetActive(true);
}
public void qc_button()
{
foreach (LineRenderer i in wt)
{
Destroy(i);
}
}
public void button_green()
{
color= Color.green;
}
public void tuic_button()
{
abc = false;
qc.SetActive(false);
green.SetActive(false);
tuic.SetActive(false);
}
}