Event Manager and Event Listener



我已经读完关于事件的文件,看着一对夫妇的教程,但是还有一些我仍然不握。在我见过的Event Managers事件管理器示例,将触发该事件的方法是在同一个class 作为事件管理器。喜欢这个:

using UnityEngine;
 using System.Collections;
 
 public class EventManager : MonoBehaviour {
     
     public delegate void CheckpointHandler(int id);
     public static event CheckpointHandler checkpointReached;
 
     void OnGUI () {
     
         if( GUI.Button(new Rect(5,5,150,40),"Checkpoint")){
             checkpointReached(555);
         }
         
     }
 
 }

所以在这里,EventManager 不仅定义委托和事件,而且还创建一个按钮,将触发该事件。

这是什么让我困惑。以为 EventManager 将什么也不做只是是定义的事件。然后你会解雇那些来自其他脚本的事件。有没有办法做到这一点吗?

我不喜欢此示例设置,因为它似乎必须将"EventManager"脚本附加到每个可能可以触发事件的对象的方式。如果有多个对象,可以引发同一事件吗?我需要将相同的"EventManager"附加到每一个人吗?

我想我可能会回答我自己的问题,但也许有人可以告诉我,是否这将执行成功与否。

我成立了 EvenManager 中的事件触发器,作为公共方法,然后使用拖放的方法将 EventManager 置于其他类,使其方法可为任何想要触发的事件。所以我的设置如下所示 (所有这些都连接到独立游戏对象):

using UnityEngine;
 using System.Collections;
 
 public class EventManager : MonoBehaviour {
 //Here I define the delegates, events and the triggers that can be called to fire the event.
     
     public delegate void CheckpointHandler(int id);
     public static event CheckpointHandler checkpointReached;
 
     
     public void hitCheckpoint (int id){
         if (checkpointReached != null)
             checkpointReached(id);
     }
 }
 using UnityEngine;
 using System.Collections;
 
 public class EventTrigger : MonoBehaviour {
 /******
 In this class I can set up a method that will access the EventManager 
 (which has been dropped onto the em variable) 
 and fire the hitCheckpoint method, 
 which in turn sends the checkpointReached event.
 ******/
     
     
     public EventManager em;
 
     void OnGUI () {
     
         if( GUI.Button(new Rect(5,5,150,40),"Checkpoint    ")){
             em.hitCheckpoint(555);
         }
         
     }
 }

 using UnityEngine;
 using System.Collections;
 
 public class EventListener : MonoBehaviour {
     //This script listens for the event and prints a message to the log.
     
     void OnEnable () {
         EventManager.checkpointReached += HandleEventManagercheckpointReached;
     }
     
     void OnDisable(){
         EventManager.checkpointReached -= HandleEventManagercheckpointReached;
     }
 
     void HandleEventManagercheckpointReached (int id)
     {
         Debug.Log ("Checkpoint reahed. ID is: " + id);
     }
 }








已标记关键词 清除标记
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页