Unity - 图形辅助线

Unity - 图形辅助线


游戏开发中使用图形辅助线可以比较直观的测试相关功能,能让策划根据辅助线配值等,也有一些InGame Debug方便后期测试。

Unity中常用的编辑器图形辅助线类

  • Gizmos
  • Handles

    两者可以在MonoBehaviour脚本的OnDrawGizmos()和OnDrawGizmosSelected()中使用:

#if UNITY_EDITOR
        private void OnDrawGizmos() // 在Scene视图实时显示
        {
            Gizmos.color = Color.yellow;
            Gizmos.DrawCube(transform.position, Vector3.one);
            UnityEditor.Handles.color = Color.yellow;
            UnityEditor.Handles.DrawWireCube(transform.position, 2 * Vector3.one);
        }

        private void OnDrawGizmosSelected() // 在Scene视图选中时显示
        { 
            Gizmos.color = Color.yellow;
            Gizmos.DrawCube(transform.position, Vector3.one);
            UnityEditor.Handles.color = Color.yellow;
            UnityEditor.Handles.DrawWireCube(transform.position, 2 * Vector3.one);
        }
#endif

其中Handles类有些高级用法,需要为MonoBehaviour脚本创建Editor类,可以结合对Inspector的扩展来使用:

[CustomEditor(typeof(Player))]
    public class PlayerEditor : UnityEditor.Editor
    {
        Player myHandles;
        GUIStyle style;
        void OnEnable()
        {
            style = new GUIStyle();
            style.richText = true;
            style.fontSize = 20;
            style.alignment = TextAnchor.MiddleCenter;
            myHandles = (Player)target;
        }

        private void OnSceneGUI() // 选中时在Scene视图创建一个可调节Radius的Handle,调节后Player的radius值会改变
        {
            Handles.color = Color.white;
            myHandles.radius = UnityEditor.Handles.RadiusHandle(Quaternion.identity, myHandles.transform.position, myHandles.radius);
        }
    }

其最常见的用处是显示攻击范围,效果图:
这里写图片描述

Unity中常用的Runtime图形辅助线类

除了编辑器模式下,运行时,也有相关方法可以显示图形:

  • Graphics.DrawMesh - Update
  • Graphics.DrawTexture - OnGUI
  • GL - OnRenderObject / OnPostRender

不过由于偏底层些,需要根据项目的需求自己封装。

猜你喜欢

转载自blog.csdn.net/Teddy_k/article/details/82117420