Prefab으로 만들어둔 버튼 UI가 있는데 마우스커서 가 오버랩 되면 정보를 띄어주는 UI가 오버레이 되는 기능을 구현하고 싶었다...

게임을 예로 들면 인벤토리 내의 아이템위에 커서를 위치하면 아이템의 정보창이 뜨는 그런 기능,,,

 

기존의 RayCastHit 으로 가져올려는데 아무리 해봐도 안됨....

 

근데 당연히 안됬던 것!

 

UI는 Rect transform 인데 transform으로 가져올려니까 안됬던 것.

찾아보니 UI는 GraphicRaycaster를 따로 사용하는데 인자값도 다르다...

PointerEventData 와 List<RayCastResult>를 인자로 사용하는데

List<RayCastResult>는 결과값을 저장하기 위한 용도로 인식이 되지만 PointerEventData는 감이 잡히질 않아

찾아보면 UI 요소와의 상호작용 및 터치/마우스 입력 이벤트 처리에 사용된다고 기술되어있다

https://docs.unity3d.com/2019.1/Documentation/ScriptReference/EventSystems.PointerEventData.html

 

Unity - Scripting API: PointerEventData

You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see: You've told us there are code samples on this page which don't work. If you know ho

docs.unity3d.com

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

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

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

    void Update()
    {
        //Check if the left Mouse button is clicked
        if (Input.GetKey(KeyCode.Mouse0))
        {
            //Set up the new Pointer Event
            m_PointerEventData = new PointerEventData(m_EventSystem);
            //Set the Pointer Event Position to that of the mouse position
            m_PointerEventData.position = Input.mousePosition;

            //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("Hit " + result.gameObject.name);
            }
        }
    }
}

유니티 공식 문서에 있는 예제코드

 

GraphicRaycaster가 Canvas에서 오브젝트를 체크해야되기에 당연히 스크립트가 Canvas 오브젝트에 붙어있다는 가정하에 작성된 코드였지만 이거 못보고 30분동안 null값만 들어와서 해맷다....

 

결론

GraphicRaycaster를 굳이 사용하지않고

인벤토리를 예시로 하자면, 버튼 UI위에 아이템 GameObject를 생성시키고 일반적인 RayCaster로 Hit된 아이템 오브젝트를 가져와서 그 아이템이 가지고 있는 정보들을 표시해주는 것이 가장 좋을 것 같다.

 

 

'Unity' 카테고리의 다른 글

[Unity #] Snap 기능 구현??  (0) 2024.03.11
[Unity #] 유니티에서 Font-awesome 사용하기  (0) 2024.01.29
[Unity #] Rigidbody? Collider?  (1) 2024.01.23
[Unity] SerializeField ? 직렬화 ?  (0) 2024.01.22
[Unity C#] Vector3  (0) 2024.01.22

+ Recent posts