DEV Community

KOGA Mitsuhiro
KOGA Mitsuhiro

Posted on • Originally published at qiita.com

Unityでオフセット値などを3Dカーソルで調整したい

はじめに

UnityでGameObjectの配置場所をオフセットでずらしたい時にフィールドを用意しておくとInspectorから調整できます。しかしVector3を斜めにずらしたい時など、数値だけでは調整が難しい場合もあります。そんな時にエディター拡張入門でGizmoとHandleを作る方法を見付けて、簡単なエディター拡張を作るとすごく便利でした。

エディター拡張の作り方

以下のようなクラスがありoffsetを3Dカーソルで調整したいとします。

using UnityEngine;

public class Body : MonoBehaviour
{
    /// <summary>
    /// 3Dカーソルを作りたいフィールド
    /// </summary>
    public Vector3 offset;
}

Enter fullscreen mode Exit fullscreen mode

以下のようなエディター拡張を作ると3DカーソルとギズモをScene Viewに作ることができます。

#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;

/// <summary>
/// 操作したいクラスをCustomEditorAttributeのtypeofで指定する
/// </summary>
[CustomEditor(typeof(Body))]
public class BodyEditor : Editor
{
    /// <summary>
    /// 3Dカーソルを作る
    /// </summary>
    private void OnSceneGUI()
    {
        var component = target as Body;
        var offset = component.offset;
        var transform = component.transform;
        offset = Handles.PositionHandle(transform.TransformPoint(offset), transform.rotation);
        component.offset = transform.InverseTransformPoint(offset);
    }

    /// <summary>
    /// ギズモを作る
    /// </summary>
    /// <param name="body"></param>
    /// <param name="gizmoType"></param>
    [DrawGizmo(GizmoType.NonSelected | GizmoType.Active)]
    private static void DrawEyeTargetGizmos(Body body, GizmoType gizmoType)
    {
        var transform = body.transform;
        Gizmos.color = Color.gray;
        Gizmos.DrawSphere(transform.TransformPoint(body.offset), 0.05f);
    }
}
#endif
Enter fullscreen mode Exit fullscreen mode

image.png

参考リンク

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Please show some love ❤️ or share a kind word in the comments if you found this useful!

Got it!