출처 : ( 링크1 ) ( 링크2 )

UI에서 이미지 없이 이벤트 받고싶을때 사용하면 좋은 콜라이더

참고 사이트의 소스를 적용해보고 UI Canvas환경(Canvas Scale, RectPosition 등등..)에 맞지 않는 부분을 수정하였음.



using UnityEngine;
using UnityEngine.UI;

[ExecuteInEditMode]
public class RaycastCollider : Graphic
{
    private RectTransform rect;
    

    public override void SetMaterialDirty() { return; }
    public override void SetVerticesDirty() { return; }

    protected override void OnPopulateMesh(VertexHelper vh)
    {
        vh.Clear();
        return;
    }

    private new void Awake()
    {
        base.Awake();
        //rect = GetComponent(typeof(RectTransform)) as RectTransform;
        rect = GetComponent<RectTransform>();
    }

    private void OnDrawGizmosSelected()
    {
        if (rect != null)
        {
            Vector3 scale = canvas.transform.localScale;
            Vector3 pos = rect.transform.position;

            Vector2 size = rect.sizeDelta;
            float xDist = (rect.rect.width * 0.5f) * scale.x;
            float yDist = (rect.rect.height * 0.5f) * scale.y;

            Vector3 leftUp = new Vector3(pos.x - xDist, pos.y + yDist, pos.z/* + zDist*/);
            Vector3 rightUp = new Vector3(pos.x + xDist, pos.y + yDist, pos.z/* + zDist*/);
            Vector3 leftDown = new Vector3(pos.x - xDist, pos.y - yDist, pos.z/* + zDist*/);
            Vector3 rightDown = new Vector3(pos.x + xDist, pos.y - yDist, pos.z/* + zDist*/);

            Gizmos.color = Color.green;
            Gizmos.DrawLine(leftUp, rightUp);
            Gizmos.DrawLine(rightUp, rightDown);
            Gizmos.DrawLine(rightDown, leftDown);
            Gizmos.DrawLine(leftDown, leftUp);
        }
    }
}

추가로 Editor 소스


using UnityEngine;
using UnityEditor;
using UnityEditor.UI;

[CanEditMultipleObjects, CustomEditor(typeof(RaycastCollider), false)]
public class RaycastColliderEditor : GraphicEditor
{
    public override void OnInspectorGUI()
    {
        base.serializedObject.Update();
        EditorGUILayout.PropertyField(base.m_Script, new GUILayoutOption[0]);
        base.RaycastControlsGUI();
        base.serializedObject.ApplyModifiedProperties();
    }
}


+ Recent posts