如何使用Handles.Label在Scene视图中绘制文本

时间:2017-02-24 16:40:47

标签: c# unity3d unity5

我可以使用Debug.DrawLine在对象之间绘制线条。 但现在我想在每个航路点上方/上方绘制/写入一个数字。 因此,在场景视图中,我将在每个航点上看到1,2,3,4 ....

我尝试添加DrawGizmo但不确定如何在Update函数中使用它并且我在使用Gizmo时收到一些警告:

第一个警告是删除每个UnityEditor以使其简化: 所以我用UnityEditor删除了所有的地方。然后我收到警告:

  

严重级代码描述项目文件行抑制状态   警告CS0618'GizmoType.SelectedOrChild'已废弃:'使用   InSelectionHierarchy(UnityUpgradable) - >   InSelectionHierarchy'

所以不确定如何使用这个Gizmo。

void Update()
    {
        if (MyCommands.walkbetweenwaypoints == true)
        {
            WayPointsAI();
        }
        // create lines between each checkpoint //
        for (int i = 0; i < waypoints.Length - 1; i++)
        {
            Debug.DrawLine(waypoints[i].transform.position, waypoints[i + 1].transform.position, Color.blue);

        }

        // create line between original transform start position 
        // and the current transform position //
        Debug.DrawLine(originalPosition, transform.position, Color.red);

        // create a line between current transform position and the next waypoint target
        // each time reached a waypoint.
        Debug.DrawLine(target.transform.position, myTransform.position, Color.green);
    }

    [UnityEditor.DrawGizmo(GizmoType.SelectedOrChild | UnityEditor.GizmoType.NotSelected)]
    static void DrawGameObjectName(Transform transform, UnityEditor.GizmoType gizmoType)
    {
        Handles.Label(transform.position, transform.gameObject.name);
    }

1 个答案:

答案 0 :(得分:0)

使用Handles.Label很棘手。

假设您的脚本名称为WayPointScript。以下是它的样子:

[ExecuteInEditMode]
public class WayPointScript : MonoBehaviour
{
    public GameObject[] waypoints;

    void Update()
    {
        if (MyCommands.walkbetweenwaypoints == true)
        {
            WayPointsAI();
        }
        // create lines between each checkpoint //
        for (int i = 0; i < waypoints.Length - 1; i++)
        {
            Debug.DrawLine(waypoints[i].transform.position, waypoints[i + 1].transform.position, Color.blue);

        }

        // create line between original transform start position 
        // and the current transform position //
        Debug.DrawLine(originalPosition, transform.position, Color.red);

        // create a line between current transform position and the next waypoint target
        // each time reached a waypoint.
        Debug.DrawLine(target.transform.position, myTransform.position, Color.green);
    }
}

注意到它上面的[ExecuteInEditMode]必须在那里。

现在,您可以使用以下代码与Text一起绘制Handles.Label

[CustomEditor(typeof(WayPointScript))]
public class TextDrawer : Editor
{

    void OnSceneGUI()
    {

        Debug.Log("Running");
        WayPointScript t = target as WayPointScript;

        //Create Text on each checkpoint //
        for (int i = 0; i < t.waypoints.Length; i++)
        {
            UnityEditor.Handles.Label(t.waypoints[i].transform.position, (i + 1).ToString());
        }
    }
}

您希望文本在顶部吗?将偏移量添加到t.waypoints[i].transform.position变量的y轴。