Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

はじめに

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

エディター拡張の作り方

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

Body.cs
using UnityEngine;

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

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

BodyEditro.cs
#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

image.png

参考リンク

kadinche
弊社では 2008年の会社設立当初から、一貫して VR ソリューションの研究開発に取り組んでいます。
https://www.kadinche.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした