【问题标题】:Display current's hovered object property/name in Unity and C#在 Unity 和 C# 中显示当前的悬停对象属性/名称
【发布时间】:2019-08-14 03:57:41
【问题描述】:

假设我有 5 个按钮,每个按钮都有不同的名称(即“红色”、“蓝色”等) 我想创建一个函数,当您将鼠标悬停在按钮上时,它将“textToDisplay”文本属性更改为当前悬停的按钮名称。

完整示例: 您有一个显示“无”的文本,但如果您将鼠标悬停在具有“红色”名称的按钮上,该文本将自行更改为“红色”。

我可以创建与按钮一样多的功能,并将每个功能与每个按钮单独匹配,但这并不是一个好方法,不是吗?

TL:DR : 我想获取当前的悬停对象属性。

【问题讨论】:

  • 您能否向我们展示您当前正在处理的将鼠标悬停在按钮上的代码?
  • 要实现这一点,我认为您可能需要从用于按钮的类派生/扩展。如果我没记错的话,应该有一个“OnHover()”类型的事件来覆盖。

标签: c# unity3d


【解决方案1】:

您可以使用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
}

【讨论】:

  • 你真是太棒了!现在一切都像魅力一样,非常感谢!会记得使用这个功能!
猜你喜欢
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-21
  • 1970-01-01
  • 1970-01-01
  • 2011-07-11
相关资源
最近更新 更多