Use event/delegation mechanism (EVENT/DELEGATE) for communication between gameobject in unity

Source: Internet
Author: User


Use event/delegation mechanism (EVENT/DELEGATE) for communication between gameobject in unity
Welcome to Unity Learning,Unity training ,UnityEnterprise TrainingEducation Area, there are manyu3d Resources,u3d Training Video,u3d Tutorials,U3d Frequently Asked questions,u3d Project Source code, the "Dog Planing Learning Network" Unity's Ultimate Academy, dedicated to building the industry unity3d Training , learning the first brand.  


Introduction
In the previous two articles:
We learned about the Sprite,animation,rigidbody and collider in 2D, and in the process of continuing to develop the game, we encounter such problems as how to handle the mutual calls between Gameobject, For example, in the Flappybird we when the bird knocked down the pipe, to the message to many gameobject, the tube received this message need to stop the movement, the UI received this message to pop gameover words. Next, let me talk about how to solve this problem rationally. Related source code reference: Flappy Bird source code.
Why do I have to communicate between Gameobject?
In game development we often encounter such a problem, in the game occurred an event, how we inform the other Gameobject: In the event of an explosion in the game, we need to be within a certain range of gameobject aware of the incident. Sometimes, we want objects other than the camera not to be notified of our event. The colorful world in the game is composed of communication mechanism.
One way to do this is to save all Gameobject that are interested in the event as member variables in the Script component in the Start method of the event's gameobject, so we take the object of the event as a subject, Object that is interested in the event as observer.
Storing observer as a member variable in subject has the disadvantage of:
Difficult to change, once you have to add a observer you need to change the code in the subject
Nullreferernceexception occurs if the observer is destroyed and cannot be removed from the subject.
When an event occurs, the code to invoke the corresponding handle method in the different observer becomes tedious and cumbersome.
Fortunately, we can solve this problem by introducing the observer pattern, and better yet, the C # built-in has a great event/delegation mechanism that makes it very easy to construct the Observer pattern.

Standard delegate types in C #
When we build the event/delegate mechanism, we first define the delegate type, referring to the cccallback in Cocos2d-x, I first defined the following three types of delegates:
The delegate does not pass any parameters
public delegate void Callfunc ();
The delegate passes in the Gameobject that the event occurred, that is, sender
public delegate void Callfunco (Gameobject sender);
The delegate passes in the Gameobject that the event occurred, sender. and a variable-length parameter list
public delegate void Callfuncop (gameobject sender, EventArgs args);
But I find that C # itself has provided a good delegate type: EventHandler, so I've replaced the delegate in the game with the delegate.
public delegate void EventHandler (object sender, EventArgs e);
Another better way to delegate is to use the generic parameter's delegate type: Eventhandlerteventargs, whose signature is as follows:
public delegate void Eventhandlerteventargs (
Object sender,
Teventargs E
)
Publish Events with EventHandler mode
If this event does not produce any extra parameters (that is, except for the sender of the event), a eventargs.empty is passed to the second parameter of EventHandler when it is called.
If additional parameters are generated, the second parameter is a type derived from EventArgs and provides all fields or properties that require the event data to be saved. The advantage of using Eventhandlerteventargs is that if events generate event data, you do not need to write your own custom delegate code.
Let's give an example to confirm the use of EventHandler:
Using System;
Namespace ConsoleApplication1
{
Class Program
{
static void Main (string[]
Args
{
Counter C = new Counter (new Random (). Next (10));
A delegate function was added to the event
c.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, Thresholdreachedeventargs e)
{
Console.WriteLine ("The Threshold of {0} is 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)
{
Eventhandlerthresholdreachedeventargs handler = thresholdreached;
if (handler! = null)
{
Handler (this, e);
}
}
An event with a generic parameter was added
public event Eventhandlerthresholdreachedeventargs thresholdreached;
}
public class Thresholdreachedeventargs:eventargs
{
public int Threshold {get; set;}
Public DateTime timereached {get; set;}
}
}

The application in the game
We use a bird to knock down a tube as an example of how to communicate:


In this scenario, we first set up two events for the bird, the score plus One (scoreadd) and the bird hitting the tube game end (Gameover) as follows:
Using Unityengine;
Using System.Collections;
Using System;
public class Birdcontroller:monobehaviour {
public event EventHandler Gameover;
public event EventHandler Scoreadd;
When leaving empty trigger, distribute the Scoreadd event
void ontriggerexit2d (collider2d col) {
if (Col.gameObject.name.Equals ("Empty")) {
if (scoreadd! = null)
Scoreadd (this, eventargs.empty);
}
}
Distribute the Gameover event when the collision begins
void oncollisionenter2d (collision2d col)
{
rigidbody2d.velocity = new Vector2 (0, 0);
if (Gameover! = null)
Gameover (this, eventargs.empty);
this.enabled = false;
}
}
Then the gameobject, interested in this event, will listen to the event through the corresponding handler, so that a one-to-many gameobject communication can occur.
Using Unityengine;
Using System.Collections;
Using System;
public class Tubecontroller:monobehaviour {
Use this for initialization
void Start () {
Gameobject.find ("Bird"). Getcomponentbirdcontroller (). Gameover + = Ongameover;
}
void OnDestroy () {
if (Gameobject.find ("Bird"))
Gameobject.find ("Bird"). Getcomponentbirdcontroller (). Gameover-= Ongameover;
}
void Ongameover (object sender, EventArgs e)
{
rigidbody2d.velocity = new Vector2 (0, 0);
}
}

For more information, please visit the "Dog Planing Learning Network" Unity Ultimate Academy Http://edu.gopedu.com

Statement: This document comes from the "Dog Planing Learning Network" Community-unity Extreme College, is a self-published Unity3d study articles, if anything violates your relevant interests, please communicate with the official, we will deal with the real-time.

Use event/delegation mechanism (EVENT/DELEGATE) for communication between gameobject in unity

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.