问题描述
我很难将触发的事件连接到另一个类中的订阅者方法。这是整个设置:
首先,我得到了这个充当发布者类的类:
public class OpenInteraction : IInteraction
{
public event EventHandler<bool> OpenStateChange;
private void OnopenStateChange(bool e)
{
Debug.Log("open = " + e);
OpenStateChange?.Invoke(this,e);
}
}
public class AttachedContainer : MonoBehavIoUr
{
private OpenInteraction openInteraction;
public void Start()
{
Debug.Log("create OpenInteraction in AttachedContainer");
openInteraction = new OpenInteraction();
openInteraction.OpenStateChange += ContainerOpened;
}
static void ContainerOpened(object sender,bool e)
{
Debug.Log("container state changed");
}
}
对于一些上下文,每次我在游戏中打开/关闭容器时都会触发该事件。当播放器执行此操作并且调试控制台显示消息“open = ..”时,方法 OnopenStateChange(bool e)
会被正确调用
在游戏开始时在每个 AttachedContainer 上创建一个 openInteraction,消息“在 AttachedContainer 中创建 OpenInteraction”也在此处适当记录。
但是,我从未在订阅者方法中看到消息“容器状态已更改”,应该在每次关闭/打开交互时触发。
这段代码有什么问题?
解决方法
调用该事件的OpenInteraction类的实例,与Class AttachedContainer中该类的实例必须是同一个。