unity/유니티 초보

Unity3D - Custom Editor 제작

rimugiri 2024. 1. 12. 14:57
728x90

사용 이유

  • Editor Mode에서 GameObject의 크기를 조정하거나 이동시킬수 있다.
  • 이러한 조정을 Script에 적용하고 싶은때 사용하는 방법이 Custom Editor이다.

카메라 제어를 통한 예제

1. 기본 스크립트

카메라 위치 제어 코드

using UnityEngine;

public class TestCamera : MonoBehaviour
{
    public float height = 5.0f;
    public float distance = 5.0f;
    public Transform target;

    private void LateUpdate()
    {
        CameraUpdate();
    }
    public void CameraUpdate()
    {
        transform.position = target.position + (Vector3.up * height) + (Vector3.forward * -distance);
    }
}

2. 에디터 스크립트

using UnityEditor;
using UnityEngine;

// 사용을 위해 필수적으로 구현
[CustomEditor(typeof(TestCamera))]
public class TestCamera_SceneEditor : Editor
{
    private TestCamera targetCamera;
    private float handlerSize = 5f;
    public override void OnInspectorGUI()
    {
        targetCamera = (TestCamera)target;
        base.OnInspectorGUI();
    }
    private void OnSceneGUI()
    {
        if (!targetCamera || !targetCamera.target) return;
        Transform cameraTarget = targetCamera.target;
        Vector3 cameraPosition = cameraTarget.position + (Vector3.up * targetCamera.height) + (Vector3.forward * -targetCamera.distance);

        Vector3 targetPosition = cameraTarget.position;
        targetPosition.y += 1.0f;

        // 빨간색 원반 생성
        Handles.color = new Color(1f, 0f, 0f, 0.15f);
        // targetPosition 에서 y축을 기준으로 distance 크기만큼 생성
        Handles.DrawSolidDisc(targetPosition, Vector3.up, targetCamera.distance);


        // 거리조정 핸들러 생성
        Handles.color = new Color(0f, 1f, 0f, 0.5f);
        targetCamera.distance = Handles.ScaleSlider(targetCamera.distance,
            targetPosition,
            -cameraTarget.forward,
            Quaternion.identity,
            handlerSize,
            0.1f
            );
        targetCamera.distance = Mathf.Clamp(targetCamera.distance, 2f, float.MaxValue);

        // 높이조정 핸들러 생성
        Handles.color = new Color(1f, 0f, 0f, 0.5f);
        targetCamera.height = Handles.ScaleSlider(targetCamera.height,
            targetPosition,
            Vector3.up,
            Quaternion.identity,
            handlerSize,
            0.1f
            );
        targetCamera.height = Mathf.Clamp(targetCamera.height, 2f, float.MaxValue);

        // Update를 통해 화면 갱신
        // 에디터상 카메라의 움직임을 나타내기위해 필요
        targetCamera.CameraUpdate();
    }
}

3. 실행 예시

0
실행예

 

728x90