首页 > 代码库 > Unity路线绘制Tool

Unity路线绘制Tool

在制作NPC汽车的路线,摆点->放入数组->画线;每个点放入数组很浪费时间,所以我考虑把所有点放入一个父级,以此来在edito模式的时候,动态获取所有点信息,然后绘制路线。

我这里以脚本的enable状态来控制数组元素的获取。

 1 using UnityEngine; 2 using System.Collections; 3  4 /// <summary> 5 /// 自定义绘制路线工具: 6 /// parentObject: 路线点的父亲对象,需要把Hierachy面板的路线赋值给parentObject 7 /// pointCounts:路线点数量 8 /// childObjects: 储存父亲下层子集路点对象集 9 /// </summary>10 [ExecuteInEditMode]11 public class DrawRoadLine : MonoBehaviour {12     public GameObject parentObject;13     public int pointCounts;14     public GameObject[] childObjects;15     //初始化脚本状态16     void Awake()17     {18         this.enabled = false;19     }20     //激活状态动态读取路点21     void OnEnable()22     {23         pointCounts = parentObject.GetComponentsInChildren<Transform>().Length - 1;24         childObjects = new GameObject[pointCounts];25         string path = parentObject.name;26         Debug.Log(path);27         for (int i = 0; i < pointCounts; i++)28         {29             childObjects[i] = GameObject.Find(path + "/Point_" + i);30         }31         32     }33     //绘制封闭路线34     void OnDrawGizmos()35     {36         if(pointCounts <= 0)37             return;38         Gizmos.color = Color.yellow;39         for (int i = 0; i < pointCounts; i++)40         {41             if (i < pointCounts - 1)42             {43                 Gizmos.DrawLine(childObjects[i].transform.position, childObjects[i + 1].transform.position);44             }45             else46             {47                 Gizmos.DrawLine(childObjects[i].transform.position, childObjects[0].transform.position);48                 break;49             }50         }51     }52     53 54 }

 

Unity路线绘制Tool