[Unity3D skills] Use event/delegate mechanism (event/delegate) in Unity to communicate between gameobjects.

Source: Internet
Author: User

Author: Wang Xuan Yi, source: http://www.cnblogs.com/neverdie/Reprinted, Please keep this statement. If you like this article, click [recommendation ]. Thank you!

// This delegate does not pass any parameter public delegate void CallFunc (); // This delegate will pass in the GameObject in which the event occurs, that is, senderpublic delegate void CallFuncO (GameObject sender ); // The delegate will pass in the event-related GameObject, that is, sender. And a variable-length parameter list public delegate void CallFuncOP (GameObject sender, EventArgs args );

However, I found that C # itself already provides a better delegate type: EventHandler, So I replaced all the delegates in the game with this delegate.

public delegate void EventHandler(object sender, EventArgs e);
Another better way to delegate is to use the generic parameter delegation type: EventHandler <TEventArgs>. The signature is as follows:
public delegate void EventHandler<TEventArgs>(    Object sender,    TEventArgs e)
Event publishing in EventHandler Mode

If this event does not generate any additional parameters (except the event sender), you can pass an EventArgs. Empty to the second parameter of EventHandler during the call.

If additional parameters are generated, the second parameter is a type derived from EventArgs and provides all fields or attributes to save event data. The advantage of using EventHandler <TEventArgs> is that if an event generates event data, you do not need to write your own custom delegate code.

The following is an example to demonstrate EventHandler's usage:

 

Using System; namespace ConsoleApplication1 {class Program {static void Main (string [] args) {Counter c = new Counter (new Random (). next (10); // added a delegate Function c to the event. thresholdReached + = c_ThresholdReached; Console. writeLine ("press 'A' key to increase total"); while (Console. readKey (true ). keyChar = 'A') {Console. writeLine ("adding one"); c. add (1) ;}} static void c_ThresholdReached (object sender, Thresho LdReachedEventArgs e) {Console. writeLine ("The threshold of {0} was reached at {1 }. ", e. threshold, e. timeReached); Environment. exit (0) ;}} class Counter {private int threshold; private int total; public Counter (int passedThreshold) {threshold = passedThreshold;} public void Add (int x) {total + = x; if (total> = threshold) {ThresholdReachedEventArgs args = new ThresholdReachedEventArgs (); args. Threshold = threshold; args. timeReached = DateTime. now; OnThresholdReached (args) ;}} protected virtual void OnThresholdReached (ThresholdReachedEventArgs e) {EventHandler Applications in games

We use a bird to knock down a pipe to illustrate how to communicate:

Using UnityEngine; using System. collections; using System; public class BirdController: MonoBehaviour {public event EventHandler GameOver; public event EventHandler ScoreAdd; // when the Empty Trigger is left, ScoreAdd event void Merge (Collider2D col) is distributed) {if (col. gameObject. name. equals ("empty") {if (ScoreAdd! = Null) ScoreAdd (this, EventArgs. empty) ;}}// when the collision starts, dispatch the GameOver event void OnCollisionEnter2D (Collision2D col) {rigidbody2D. velocity = new Vector2 (0, 0); if (GameOver! = Null) GameOver (this, EventArgs. Empty); this. enabled = false ;}}

 

Then, the GameObject that is interested in this event listens to the event through the corresponding Handler, so that one-to-many GameObject communication can be performed.

 

using UnityEngine;using System.Collections;using System;public class TubeController : MonoBehaviour {    // Use this for initialization    void Start () {        GameObject.Find("bird").GetComponent<BirdController>().GameOver += OnGameOver;    }    void OnDestroy() {        if ( GameObject.Find("bird") )            GameObject.Find("bird").GetComponent<BirdController>().GameOver -= OnGameOver;    }    void OnGameOver(object sender, EventArgs e)    {        rigidbody2D.velocity = new Vector2(0, 0);    }}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.