コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】EventSystem.current.IsPointerOverGameObject が検出したゲームオブジェクトを取得する方法

概要

using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Kogane
{
    public sealed class CustomStandaloneInputModule : StandaloneInputModule
    {
        [CanBeNull]
        public GameObject GetLastPointerGameObject()
        {
            return GetLastPointerGameObject( kMouseLeftId );
        }

        [CanBeNull]
        public GameObject GetLastPointerGameObject( int pointerId )
        {
            var lastPointer = GetLastPointerEventData( pointerId );
            return lastPointer?.pointerCurrentRaycast.gameObject;
        }
    }
}

上記のような独自の StandaloneInputModule を作成して

シーンに存在する EventSystem にアタッチする

var gameObject = Application.isEditor
        ? m_eventSystem.GetLastPointerGameObject()
        : m_eventSystem.GetLastPointerGameObject( Input.GetTouch( 0 ).fingerId )
    ;

あとは上記のようなコードで取得できる

参考サイト様