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

参考リンク

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay