当前位置:网站首页>Passing values between classes using delegates and events
Passing values between classes using delegates and events
2022-06-30 04:53:00 【LintonL】
Not very clear , All kinds of Google ~
You need to prepare two inheritance and MonoBehaviour Of EventDispatcher Classes and EventListener class .
I'll come here delegate It's written in EventDispatcher In the , You can also create a new class delegate In it , Make it convenient ...
// Define delegate events , It defines the types of methods that can be represented /** event */ public delegate void EventHandler(GameObject e); /** collision detection */ public delegate void CollisionHandler(GameObject e,Collision c); /** Trigger detection */ public delegate void TriggerHandler(GameObject e,Collider other); /** Controller collision detection */ public delegate void ControllerColliderHitHandler(GameObject e,ControllerColliderHit hit); /** New levels are loaded */ public delegate void LevelWasLoadedHandler(GameObject e,int level);

Then rewrite MonoBehaviour Those time response functions supported :
such as OnMouseDown();
So let's define a EventHandler This delegated event ... And then again OnMouseDown Operate on him in the response function ..
If a GameObject Listens for this event and writes the response function ( The response function is the definition The event entrust delegate), So in rewriting OnMouseDown The function class will call and execute this passed in delegate And the this.gameObject Spread it out .
public event EventHandler MouseDown; void OnMouseDown(){ if (MouseDown != null) MouseDown (this.gameObject); }
And so on , Enclosed EventDispatcher class :
using System; using UnityEngine; /** * be based on MonoBehaviour An event dispatch class of * A simple event dispatcher - allows to listen to events in one GameObject from another GameObject * * * Usage: * Add this script to the object that is supposed to dispatch events. * In another objects follow this pattern to register as listener at intercept events: void Start () { EventDispatcher ev = GameObject.Find("someObject").GetComponent<EventDispatcher>(); ev.MouseDown += ListeningFunction; // Register the listener (and experience the beauty of overloaded operators!) } void ListeningFunction (GameObject e) { e.transform.Rotate(20, 0, 0); // 'e' is the game object that dispatched the event e.GetComponent<EventDispatcher>().MouseDown -= ListeningFunction; // Remove the listener } * This class does not implement all standards events, nor does it allow dispatching custom events, * but you shold have no problem adding all the other methods. * * date: 2013.8.21 */ public class EventDispatcher:MonoBehaviour{ // Define delegate events , It defines the types of methods that can be represented /** event */ public delegate void EventHandler(GameObject e); /** collision detection */ public delegate void CollisionHandler(GameObject e,Collision c); /** Trigger detection */ public delegate void TriggerHandler(GameObject e,Collider other); /** Controller collision detection */ public delegate void ControllerColliderHitHandler(GameObject e,ControllerColliderHit hit); /** New levels are loaded */ public delegate void LevelWasLoadedHandler(GameObject e,int level); public event EventHandler MouseEnter; void OnMouseEnter(){ if (MouseEnter != null) // If there is a way to register a delegate variable MouseEnter(this.gameObject); // Calling methods through delegation } public event EventHandler MouseOver; void OnMouseOver(){ if (MouseOver != null) MouseOver (this.gameObject); } public event EventHandler MouseExit; void OnMouseExit(){ if (MouseExit != null) MouseExit (this.gameObject); } public event EventHandler MouseDown; void OnMouseDown(){ if (MouseDown != null) MouseDown (this.gameObject); } public event EventHandler MouseUp; void OnMouseUp(){ if (MouseUp != null) MouseUp (this.gameObject); } public event EventHandler MouseDrag; void OnMouseDrag(){ if (MouseDrag != null) MouseDrag (this.gameObject); } /** When renderer( Renderers ) Called when visible on any camera OnBecameVisible*/ public event EventHandler BecameVisible; void OnBecameVisible (){ if (BecameVisible != null) BecameVisible (this.gameObject); } /** When renderer( Renderers ) Called when not visible on any camera OnBecameInvisible*/ public event EventHandler BecameInvisible; void OnBecameInvisible (){ if (BecameInvisible != null) BecameInvisible (this.gameObject); } public event EventHandler Enable; void OnEnable(){ if(Enable != null) Enable(this.gameObject); } public event EventHandler Disable; void OnDisable(){ if(Disable != null) Disable(this.gameObject); } public event EventHandler Destroy; void OnDestroy(){ if(Destroy != null) Destroy(this.gameObject); } /** Call... Before the camera renders the scene */ public event EventHandler PreRender; void OnPreRender(){ if(PreRender != null) PreRender(this.gameObject); } /** Call... After the camera finishes rendering the scene */ public event EventHandler PostRender; void OnPostRender(){ if(PostRender != null) PostRender(this.gameObject); } /** Called after the camera scene rendering is completed */ public event EventHandler RenderObject; void OnRenderObject(){ if(RenderObject != null) RenderObject(this.gameObject); } public event EventHandler ApplicationPause; void OnApplicationPause(){ if(ApplicationPause != null) ApplicationPause(this.gameObject); } /** Sent to all game objects when the player gains or loses focus */ public event EventHandler ApplicationFocus; void OnApplicationFocus(){ if(ApplicationFocus != null) ApplicationFocus(this.gameObject); } public event EventHandler ApplicationQuit; void OnApplicationQuit(){ if(ApplicationQuit != null) ApplicationQuit(this.gameObject); } public event TriggerHandler TriggerEnter; void OnTriggerEnter(Collider other){ if(TriggerEnter != null) TriggerEnter(this.gameObject,other); } public event TriggerHandler TriggerExit; void OnTriggerExit(Collider other){ if(TriggerExit != null) TriggerExit(this.gameObject,other); } public event TriggerHandler TriggerStay; void OnTriggerStay(Collider other){ if(TriggerStay != null) TriggerStay(this.gameObject,other); } public event ControllerColliderHitHandler controllerColliderHit; void OnControllerColliderHit(ControllerColliderHit hit){ if(controllerColliderHit != null) controllerColliderHit(this.gameObject,hit); } public event CollisionHandler CollisionEnter; void OnCollisionEnter (Collision c){ if (CollisionEnter != null) CollisionEnter (this.gameObject, c); } public event CollisionHandler CollisionStay; void OnCollisionStay (Collision c){ if (CollisionStay != null) CollisionStay (this.gameObject, c); } public event CollisionHandler CollisionExit; void OnCollisionExit (Collision c){ if (CollisionExit != null) CollisionExit (this.gameObject, c); } public event LevelWasLoadedHandler LevelWasLoaded; void OnLevelWasLoaded(int level){ if(LevelWasLoaded != null) LevelWasLoaded(this.gameObject,level); } }
First, you need to get the... On the target component EventDispatcher Components .
private EventDispatcher evt = null; // Use this for initialization void Start () { evt = GameObject.Find("Cube1").GetComponent<EventDispatcher>(); }
/** Register listener functions */ void addEventListener(){ // Assign a value to the event type variable of the delegate evt.MouseDown +=OnMouseDownListener; evt.MouseDrag += OnMouseDragLIstener; }

And then write out the processing function ...
/** Event response handler * @param GameObject e The source of the event GameObject object * <li> Parameters of the event response function , See EventDispatcher Class Handler The number of parameters * */ void OnMouseDownListener(GameObject e){ print("on mouse down.."); e.transform.Rotate(20, 0, 0); // Remove listener function e.GetComponent<EventDispatcher>().MouseDown -= OnMouseDownListener; } void OnMouseDragLIstener(GameObject e){ print("on mouse drag.."); } Copy code Enclosed EventListener Source code : using UnityEngine; using System.Collections; /** * Responding to events * */ public class EventListener : MonoBehaviour { private EventDispatcher evt = null; // Use this for initialization void Start () { evt = GameObject.Find("Cube1").GetComponent<EventDispatcher>(); addEventListener(); } /** Register listener functions */ void addEventListener(){ // Assign a value to the event type variable of the delegate evt.MouseDown +=OnMouseDownListener; evt.MouseDrag += OnMouseDragLIstener; } // Update is called once per frame void Update () { } /** Event response handler * @param GameObject e The source of the event GameObject object * <li> Parameters of the event response function , See EventDispatcher Class Handler The number of parameters * */ void OnMouseDownListener(GameObject e){ print("on mouse down.."); e.transform.Rotate(20, 0, 0); // Remove listener function //e.GetComponent<EventDispatcher>().MouseDown -= OnMouseDownListener; } void OnMouseDragLIstener(GameObject e){ print("on mouse drag.."); } }
It's done ...

There is a problem , Let's study together , Learning together , Progress together ~~

边栏推荐
- 深度学习------不同方法实现Inception-10
- HTC vive cosmos development - handle button event
- 为什么win10开热点后电脑没有网络?
- Differences between cookies and sessions
- Servlet lifecycle
- Sailing experience not to be missed in New York Tourism: take you to enjoy the magnificent city scenery from different perspectives
- A collection of errors encountered in machine learning with unity
- Singapore must visit these scenic spots during the Spring Festival
- Connect to the database and run node JS running database shows that the database is missing
- PBR material: basic principle and simple fabrication
猜你喜欢

UE4 method of embedding web pages

Beanfactory creation process

力扣349. 两个数组的交集

【Paper】2015_ Coordinated cruise control for high-speed train movements based on a multi-agent model

SSL universal domain name certificate

Create transfer generation point

【Paper】2021_ Analysis of the Consensus Protocol of Heterogeneous Agents with Time-Delays

How to renew an SSL certificate

力扣2049:统计最高分的节点数目

【Paper】2013_ An efficient model predictive control scheme for an unmanned quadrotor helicopter
随机推荐
Foreign SSL certificate
Approaching history, introduction to the London Guard Museum
【Paper】2017_ Research on coordinated control method of underwater vehicle formation marine survey
Solution to the 292 week match of Li Kou
The difference between get and post requests
brew安装nvm报nvm command not found解决方案
Lambda&Stream
Bean creation process and lazy init delay loading mechanism
What to do when the alicloud SSL certificate expires
Unreal 4 learning notes - set player birth point
UE4 method of embedding web pages
Keywords implements and @override
EasyRecovery数据恢复软件 恢复了我两年前的照片视频数据
Implementation of one interview question one distributed lock every day
One interview question a day - the underlying implementation of synchronize and the lock upgrade process
【Paper】2019_ Distributed Cooperative Control of a High-speed Train
The golden deer, a scenic spot in London -- a sailing museum that tells vivid sailing stories
Requirements for transfer transaction cases: 1 Employee 1 transfers money to employee 2. Therefore, two update sals should be executed. Purpose: either both updates are successful or both implementati
【Paper】2006_ Time-Optimal Control of a Hovering Quad-Rotor Helicopter
Detailed explanation of cookies and sessions