The use and difference of delegation and event in Unity

1, Foreword

1. What is entrustment?

A delegate is a container in which functions and methods are placed. The forms of functions are different, and the parameters and return values are different. Therefore, before you delegate, you must first define the type of function stored in the delegate container, that is, the delegate type.

After the function type is defined and the function is added to the delegate container, as long as you trigger the delegate call, the delegate will help you call every function in the container once, which is no different from calling ordinary functions.

2. What is an event?

Events are declared and generated in a class and are associated with event handlers by using delegates in the same class or other classes. The class containing the event is used to publish the event. This is called the publisher class. Other classes that accept this event are called} subscriber classes. Events use the publisher subscriber model.

2, Introduction and analysis of simple cases

1. Entrustment

Take an example to use delegation: we first define a pet name delegation and implement the methods of dog and cat in the TestA class

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public delegate void PetName(string name); //Delegate (requires a parameter of type string as pet name)

//Terrestrial animals
public class TestA : MonoBehaviour
{
    PetName petName; //Declaration delegation

    void Start()
    {
        //entrust
        petName += Dog; //dog
        petName += Cat; //cat

        //Call delegate event
        petName("Big white");

    }

    //The dog needs a string parameter because of the delegate call
    void Dog(string name)
    {
        Debug.Log($"Call me{name},It's a cat");
    }

    //cat
    void Cat(string name)
    {
        Debug.Log($"Call me{name},It's a dog");
    }
}

Operation results:

From this, we can see that when we "add" two methods (dog and cat) to the delegate, we only need to call the defined delegate (petName method) to execute the added two methods at the same time. According to the meaning of the above delegate, we create a petName delegate as a container, and then add the dog (dog) and cat (CAT) methods to the container, so that we can execute all the methods in the container only by executing the container.

2. Events

It needs to be implemented based on the previous delegate. First, we create a TestB class with two methods: Parrot(string name) parrot and Pigeon(string name) pigeon. Create an Event event at the same time.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//birds
public class TestB : MonoBehaviour
{
    public static event PetName SayHelloEvent;//event

    void Start()
    {
        //Add method to event
        SayHelloEvent = Parrot;
        SayHelloEvent += Pigeon;

        SayHelloEvent("Xiaobai");
    }

    //parrot
    public static void Parrot(string name) 
    {
        Debug.Log($"Call me{name},It's a parrot");
    }

    //dove
    public static void Pigeon(string name)
    {
        Debug.Log($"Call me{name},It's a pigeon");
    }
}

Disable the previous script TestA and drag TestB into the scene. The running effect is as follows:

3, Difference between delegation and event

Delegates are used in the same way as events, but events have many restrictions. The definitions and differences between the two are as follows:

1. When creating a delegate, the method type will be defined. (whether there are parameters and return values)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public delegate void DelegateA();               //No parameter, no return value
public delegate void DelegateB(string name);    //Return value with or without parameters
public delegate string DelegateC();             //No parameter has return value
public delegate string DelegateD(string name);  //There are parameters and return values

//Terrestrial animals
public class TestA : MonoBehaviour
{
    //Delegate definition
    DelegateA delegateA;        //No parameter, no return value
    DelegateB delegateB;        //Return value with or without parameters
    DelegateC delegateC;        //No parameter has return value        
    DelegateD delegateD;        //There are parameters and return values

    void Start()
    {
        //Add method
        delegateA = A;
        delegateB = B;
        delegateC = C;
        delegateD = D;

        //Here is an example of an error. Adding a method B to a delegateA delegate will result in an error. The reason is that the delegate defines a method type. If the method type B does not conform to the method type defined by delegateA, an error will be reported
        //delegateA += B;

        //function
        delegateA();
        delegateB("");
        delegateC();
        delegateD("");

    }

    void A() 
    {
        Debug.Log("No parameter, no return value");
    }
    void B(string name)
    {
        Debug.Log("Return value with or without parameters");
    }
    string C()
    {
        Debug.Log("No parameter has return value");
        return "";
    }
    string D(string name)
    {
        Debug.Log("There are parameters and return values");
        return "";
    }
}

Operation results:

 

Error demonstration:

2. The creation of an event requires a delegate to be declared,

3. Delegates can be declared in or outside any class, but events can only be declared in the class, as follows:

4. The event can only be used in the currently declared class. No matter whether the event is set to public or static, other classes cannot call it

In general, Event is a delegate that adds many restrictions.

IV. case use

Case 1:

Take an example that we often use. You subscribe to a blogger's column (game column) in CSDN. When the blogger publishes the latest article of this column, you will receive a message. This is the delegate used. The implementation is as follows

1. Create a Blogger class, which is responsible for writing articles and calling the delegate event to send the latest articles to the subscribing column

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


//This is a blogger class, which is responsible for writing articles and calling the delegate event to send the latest articles to the subscribing column
public class Blogger : MonoBehaviour
{
    public InputField articleName; //Article name
    public Button uploadBtn; //Upload article

    void Start()
    {
        //Button monitoring
        uploadBtn.onClick.AddListener(UpLoad);
    }

    //Upload event
    void UpLoad() 
    {
        //When the upload article name is not empty
        if (articleName.text!=string.Empty)
        {
            Debug.Log($"Bloggers upload articles:{articleName.text}");
        }
    }
}

 2. Create a subscription delegate with parameters and no return value, which is used to store the subscriber's push information method, and declare the creation in the blogger class. Combined with the above blogger class, the complete code is as follows:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public delegate void Subscribe(string name);//Subscription delegation is used to store the push method of subscribers

//Subscribing to a blog post is used to send the latest event to the blogger
public class Blogger : MonoBehaviour
{
    public InputField articleName; //Article name
    public Button uploadBtn; //Upload article

    public static Subscribe subscribe; //Create a public static subscription delegate

    void Start()
    {
        //Button monitoring
        uploadBtn.onClick.AddListener(UpLoad);
    }

    //Upload event
    void UpLoad() 
    {
        //When the upload article name is not empty
        if (articleName.text!=string.Empty)
        {
            Debug.Log($"Bloggers upload articles:{articleName.text}");
            subscribe(articleName.text); //Send information to subscribed people
        }
    }
}

3. Create two PeopleA and PeopleB personnel classes, declare the Push push message method in them, and add it to the subscription delegate in strat

PeopleA:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//Subscriber A
public class PeopleA : MonoBehaviour
{
    void Start()
    {
        Blogger.subscribe += Push; //Push method of adding person A to subscription delegate
    }

    //Push information
    void Push(string name)
    {
        Debug.Log($"I'm a staff member A,Received the latest article from blogger:{name}");
    }
}

PeopleB:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//Subscriber B
public class PeopleB : MonoBehaviour
{
    void Start()
    {
        Blogger.subscribe += Push; //Push method of adding person A to subscription delegate
    }
    //Push information
    void Push(string name) 
    {
        Debug.Log($"I'm a staff member B,Received the latest article from blogger:{name}");
    }
}

Drag the three scripts into the scene, and the layout is as follows:

Operation results:

Other cases:

https://blog.csdn.net/ChinarCSDN/article/details/80387157?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522161232462616780255284165%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=161232462616780255284165&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_v2~rank_v29-1-80387157.first_rank_v2_pc_rank_v29_10&utm_term=unity%E4%B8%AD%E5%AE%9A%E4%B9%89delegate%E5%A7%94%E6%89%98%E5%9C%A8%E5%85%B6%E4%BB%96%E8%84%9A%E6%9C%AC%E4%B8%AD%E8%B0%83%E7%94%A8&spm=1018.2226.3001.4187 

Keywords: C# Unity

Added by ultrasound0000 on Thu, 10 Mar 2022 16:44:44 +0200