본문 바로가기
카테고리 없음

Unity) 터치 된 오브젝트 확인하기(Graphic Raycaster)

by 테샤르 2022. 11. 9.

 터치 된 오브젝트 확인하기(Graphic Raycaster)

 

<설명>
그래픽스 레이캐스터는 캔버스에 레이캐스트를 하는 데 사용합니다. 레이캐스터는 캔버스의 모든 그래픽스를 감시하여 그 중 하나에 충돌하였는지 여부를 결정합니다.
그래픽 레이캐스터를 설정하여 후면 그래픽스를 무시하거나 그 앞에 있는 2D 또는 3D 오브젝트에 의해 가려지도록 설정할 수 있습니다. 이 요소의 처리 순서를 레이캐스팅의 앞이나 뒤로 변경하고 싶은 경우, 수동으로 우선 순위를 지정할 수도 있습니다.

 

Graphic Raycaster를 통해서 터치된 오브젝트에 대해서 확인을 좀더 쉽게 하는 코드이다.

EventSystem과 GraphicRaycaster를 통해서 

Touch Event를 받는 결과 RaycasterResult 의 정보를 Debug 정보로 노출시킨다.

나중에 많은 오브젝트가 쌓였을때 클릭된 오브젝트가 어떤건지 알기가 수월하다.

//Attach this script to your Canvas GameObject.
//Also attach a GraphicsRaycaster component to your canvas by clicking the Add Component button in the Inspector window.
//Also make sure you have an EventSystem in your hierarchy.

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;

public class GraphicRaycasterDebug : MonoBehaviour
{
    private GraphicRaycaster m_Raycaster;
    private PointerEventData m_PointerEventData;
    private EventSystem m_EventSystem;


    [Header("-----TouchPosition")]
    [ShowIf(ShowIfAttribute.ActionOnConditionFail.DontDraw, ShowIfAttribute.ConditionOperator.And, nameof(IsShow))]
    [SerializeField]
    private Vector3 m_TouchPosition = default;

    
    [Header("-----RaycastResult")]
    [SerializeField]
    private List<GraphicRaycasterRaycasterInfo> m_CurrentRayResult = new List<GraphicRaycasterRaycasterInfo>();

    
    private bool input;

    private bool IsShow => m_CurrentRayResult.Count > 0;

    void Start()
    {
        //Fetch the Raycaster from the GameObject (the Canvas)
        m_Raycaster = GetComponent<GraphicRaycaster>();
        m_EventSystem = GetComponent<EventSystem>();
    }

    void Update()
    {
#if UNITY_EDITOR
        if (Input.GetMouseButton(0))
        {
            m_TouchPosition = Input.mousePosition;
            input = true;
        }
#else
        if ( Input.touchCount == 1 )
        {
            m_TouchPosition = Input.GetTouch(0).position;
            input=true;
        }
#endif
        if (input == false)
            return;


        //
        { 
            m_CurrentRayResult.Clear();

            //Set up the new Pointer Event
            if(m_PointerEventData == null)
                m_PointerEventData = new PointerEventData(m_EventSystem);
            //Set the Pointer Event Position to that of the mouse position

            m_PointerEventData.position = m_TouchPosition;

            //Create a list of Raycast Results
            List<RaycastResult> results = new List<RaycastResult>();

            //Raycast using the Graphics Raycaster and mouse click position
            m_Raycaster.Raycast(m_PointerEventData, results);

            //For every result returned, output the name of the GameObject on the Canvas hit by the Ray
            foreach (RaycastResult result in results)
            {
                Debug.Log($"[GraphicRaycasterRaycasterExample] Hit : {result.gameObject.name}" +
                    $" {result.index} / {result.depth} / {result.displayIndex} ");
                m_CurrentRayResult.Add(new GraphicRaycasterRaycasterInfo(result));
            }
        }
    }
}

[System.Serializable]
public class GraphicRaycasterRaycasterInfo
{
    [SerializeField]
    private GameObject m_GameObject = default;
    [SerializeField]
    private float m_Distance = default;
    [SerializeField]
    private float m_Index = default;

    [SerializeField]
    private int m_Depth = default;
    [SerializeField]
    private int m_DisplayIndex = default;

    private RaycastResult m_RaycastResult
    {
        set
        {
            m_GameObject = value.gameObject;
            m_Distance = value.distance;
            m_Index = value.index;
            m_Depth = value.depth;
            m_DisplayIndex = value.displayIndex;
        }
    }

    public GraphicRaycasterRaycasterInfo(RaycastResult raycastResult)
    {
        m_RaycastResult = raycastResult;
    }
}

 

반응형

 

Unity Graph Raycaster : [링크]

 

그래픽 레이캐스터 - Unity 매뉴얼

그래픽스 레이캐스터는 캔버스에 레이캐스트를 하는 데 사용합니다. 레이캐스터는 캔버스의 모든 그래픽스를 감시하여 그 중 하나에 충돌하였는지 여부를 결정합니다.

docs.unity3d.com

 

사진

 

★☆☆☆☆

 

반응형

댓글