我有这样的代码
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class Area : MonoBehaviour, IPointerDownHandler
{
public Image Area;
public void OnPointerDown(PointerEventData data){ //some code...}
}
如果我在图像上添加类它工作正常,但我想将类添加到 gameMaganer 对象并将图像设置为公共(public)值 Area 并在其上获取 OnPointerDown。可能吗?
您尝试做的事情仅用一个脚本是不可能的。您至少需要两个脚本:
- 图像上的一个,实现
IPointerDownHandler
接口(interface)并引发事件,以便您的第二个脚本可以收听它
- 另一个游戏对象,监听第一个脚本引发的事件:
using UnityEngine;
using UnityEngine.EventSystems;
[System.Serializable]
public class PointerEvent : UnityEngine.Events.UnityEvent<PointerEventData> {} ;
public class PointerDownHandler : MonoBehaviour, IPointerDownHandler
{
public PointerEvent OnPointerDownEvent ;
public void OnPointerDown(PointerEventData data)
{
if( OnPointerDownEvent != null )
OnPointerDownEvent.Invoke( data ) ;
}
}
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class Area : MonoBehaviour
{
public PointerDownHandler PointerDownHandler;
private void Start()
{
OnPointerDownEvent.AddListener( OnPointerDown ) ;
}
public void OnPointerDown(PointerEventData data){ //some code...}
}
我是一名优秀的程序员,十分优秀!