您可以使用IPointerEnterHandler 并将此组件添加到Button 组件所附加到的同一GameObject。
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 以允许指针检测。对于非 UI 游戏对象上的指针检测,请确保将 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);
}
}
并在 Inspector 中引用回调方法(如 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
}