Вы можете использовать IPointerEnterHandler
и добавить этот компонент к тому же GameObject
компоненту Button
, к которому присоединен.
public class Example : MonoBehaviour, IPointerEnterHandler
{
public void OnPointerEnter(PointerEventData pointerEventData)
{
// passing in "this" as context additionally allows to
// click on the log to highlight the object where it came from
Debug.Log("Currently hovering " + name, this);
}
}
Убедитесь, что EventSystem
существует в сцене, чтобы разрешить обнаружение указателя.Для обнаружения указателя на объектах GameObject, не относящихся к пользовательскому интерфейсу, убедитесь, что PhysicsRaycaster
присоединен к Camera
.
Вы можете добавить, например, UnityEvent<string>
вЧтобы добавить обратные вызовы
[System.Serializable]
public class StringEvent : UnityEvent<string>
{
}
public class Example : MonoBehaviour, IPointerEnterHandler
{
public StringEvent OnHover;
public void OnPointerEnter(PointerEventData pointerEventData)
{
// passing in "this" as context additionally allows to
// click on the log to highlight the object where it came from
Debug.Log("Currently hovering " + name, this);
}
}
и ссылочные методы обратного вызова в Инспекторе (как с onClick
), но обратите внимание, что эти методы должны ожидать string
в качестве параметра.
Или в целевом компоненте вы можете добавить обратный вызов к каждому из этих событий, например
private void Start()
{
var buttons = FindObjectsOfType<Example>();
foreach(var button in buttons)
{
// it is always save to remove listeners even if
// they are not there yet
// this makes sure that they are only added once
button.OnHover.RemoveListener(OnButtonHovered);
button.OnHover.AddListener(OnButtonHovered);
}
}
private void OnButtonHovered(string buttonName)
{
// do something with the buttonName
}