Unity实现画线条功能

废话不多说,今天实现一个用LineRender组件实现画图的功能。网上已有相关博文,感觉步骤有些模糊,今天就整理出来供大家学习

第一步:创建一个空对象,为其添加LineRender组件。

Unity实现画线条功能

注意:将材质的着色器改为颗粒/添加剂,否则在代码里面控制颜色不起效。

二再创建一个新的对象,来挂载脚本脚本如下。:

 

[csharp]  查看普通 副本

  1. 使用UnityEngine;  
  2. 使用System.Collections;  
  3.   
  4. 公共课NewBehaviourScript:MonoBehaviour {  
  5.   
  6.     私人GameObject克隆;  
  7.     私人LineRenderer线;  
  8.     int i;  
  9.     //带有LineRender物体  
  10.     公共GameObject目标;  
  11.     void Start(){  
  12.           
  13.     }  
  14.       
  15.     //每帧调用一次Update  
  16.     void Update(){  
  17.         if(Input.GetMouseButtonDown(0)){  
  18.             //实例化对象  
  19.             克隆=(游戏物体)实例化(目标,target.transform.position,Quaternion.identity);  
  20.   
  21.             //获得该物体上的LineRender组件  
  22.             行= clone.GetComponent <LineRenderer>();  
  23.             //设置起始和结束的颜色  
  24.             line.SetColors(Color.red,Color.blue);  
  25.             //设置起始和结束的宽度  
  26.             line.SetWidth(0.2F,0.1F);  
  27.             //计数  
  28.             I = 0;  
  29.         }  
  30.         如果(Input.GetMouseButton(0))  
  31.         {  
  32.             //每一帧检测,按下鼠标的时间越长,计数越多  
  33.             我++;  
  34.             //设置顶点数  
  35.             line.SetVertexCount(ⅰ);  
  36.             //设置顶点位置(顶点的索引,将鼠标点击的屏幕坐标转换为世界坐标)  
  37.             line.SetPosition(i-1,Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y,15)));  
  38.           
  39.   
  40.         }  
  41.   
  42.     }  
  43. }  


三:将第一步建的空对象,拖入督察面板

 

Unity实现画线条功能

四:运行效果如下:

Unity实现画线条功能