Unity 2D 鼠标点击事件 Debug.Log 获取方法名称
在Unity中,你可以使用Delegate的GetInvocationList()方法获取事件的所有注册方法,并使用Method.Name属性获取方法的名称。以下是一个示例代码:
using UnityEngine;
public class InputManager : MonoBehaviour
{
public delegate void MouseClickEventHandler();
public event MouseClickEventHandler OnMouseLeftClick;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
OnMouseLeftClick?.Invoke();
}
}
}
public class PlacementManager : MonoBehaviour
{
private void Start()
{
InputManager inputManager1 = GetComponent<InputManager>();
PlacementManager placementManager1 = GetComponent<PlacementManager>();
inputManager1.OnMouseLeftClick += placementManager1.StartChange;
Debug.Log("OnMouseLeftClick is currently assigned to: " + GetDelegateMethodName(inputManager1.OnMouseLeftClick));
}
private string GetDelegateMethodName(Delegate del)
{
if (del == null)
{
return "No method assigned";
}
string methodName = "";
foreach (Delegate subDel in del.GetInvocationList())
{
methodName += subDel.Method.Name + ", ";
}
return methodName.TrimEnd(',', ' ');
}
private void StartChange()
{
// Method assigned to OnMouseLeftClick
}
}
此示例中,我们在Start()方法中使用GetDelegateMethodName()方法获取inputManager1.OnMouseLeftClick事件的注册方法的名称,并使用Debug.Log()输出到控制台。
原文地址: https://www.cveoy.top/t/topic/pPM2 著作权归作者所有。请勿转载和采集!