当前位置:网站首页>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 ~~

边栏推荐
- 一条命令运行rancher
- brew安装nvm报nvm command not found解决方案
- Software digital signature certificate
- 【Paper】2015_ Coordinated cruise control for high-speed train movements based on a multi-agent model
- Force buckle 349 Intersection of two arrays
- Method of applying for code signing certificate by enterprise
- Singapore must visit these scenic spots during the Spring Festival
- Tcp/ip protocol details Volume I (Reading Guide)
- 力扣349. 两个数组的交集
- The role of break
猜你喜欢
Using the command line to convert JSON to dart file in fluent
Meet in Bangkok for a romantic trip on Valentine's Day
HTC vive cosmos development - handle button event
Have a heart beating Valentine's day in Singapore
Qos(Quality of Service)
Unity3d realizes Google Digital Earth
SSL update method
Deeply understand the function calling process of C language
Malignant bug: 1252 of unit MySQL export
Window10 jar double click to run without response
随机推荐
How to renew an SSL certificate
Unit screenshot saved on the phone
Meet in Bangkok for a romantic trip on Valentine's Day
PS1 Contemporary Art Center, Museum of modern art, New York
Thread safety and processing caused by multithreading
【Paper】2017_ Research on coordinated control method of underwater vehicle formation marine survey
Error about the new version of UE4: unavigationsystemv1:: simplemovetoactor has been deprecated
Deep learning ----- different methods to realize inception-10
一条命令运行rancher
Moore Manor diary I: realize the reclamation, sowing, watering and harvest in Moore Manor
Have a heart beating Valentine's day in Singapore
[UGV] schematic diagram of UGV version 32
力扣27. 移除元素
Unity automatic pathfinding
Method of applying for code signing certificate by enterprise
Exploration of unity webgl
Detailed explanation of cookies and sessions
This connection is not a private connection this website may be pretending to steal your personal or financial information
Bean creation process and lazy init delay loading mechanism
Oculus quest2 development: (I) basic environment construction and guide package