0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-03-21

はじめに

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

参考リンク

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?