![](/img/trans.png)
[英]How can I display the current date and time in my C# windows form application's text property?
[英]Display current's hovered object property/name in Unity and C#
假設我有5個按鈕,每個按鈕都有不同的名稱(即“紅色”,“藍色”等),我想創建一個函數,即當您將鼠標懸停在按鈕上時,它將“ textToDisplay”文本屬性更改為當前懸停的按鈕名稱。
完整示例:您的文本顯示為“ Nothing”,但是如果將鼠標懸停在帶有“ red”名稱的按鈕上,該文本將自身變為“ red”。
我可以創建與按鈕數量一樣多的功能,並分別將每個功能與每個按鈕匹配,但這不是一個好方法,不是嗎?
TL:DR:我想獲取當前的懸停對象屬性。
您可以使用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
以允許指針檢測。 對於非UIPhysicsRaycaster
上的指針檢測,請確保將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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.