C#

delegate VS event

Naranjito 2023. 2. 21. 02:06
  • delegate

Manageable all the functions at the same time in one class.

public class part: MonoBehaviour
{
    public delegate void ChainFunction(int value); //delegate class created
    ChainFunction chain; //delegate class has been allocated to 'chain'

    int power;
    int defence;

    public void SetPower(int value)
    {
        power+=value;
        print("power has been increased as " +value+ ", total power is "+power);
    }

    public void SetDefence(int value)
    {
        defence+=value;
        print("defence has been increased as " +defence+ ", total power is "+defence);
    }

    void Start(){
        chain+=SetPower;
        chain+=SetDefence;
        if(chain!=null)
            chain(5); //all functions can put in the one basket and call it togeter
    }
}

 

  • event

Inherits the 'delegate', and functions of other classes in other scrips can be managed at once.

 

Script1. (class 1)

1. Create delegate function.

2. Create event : Inherits delefate function with static.

public class part: MonoBehaviour
{

# 1
    public delegate void ChainFunction(int value); //delegate class created

# 2
    public static event ChainFunction OnStart; //inherits 'ChainFunction' from delegate, and then event named as 'OnStart'
    //accessible from other class by declared 'static'

    int power;
    int defence;
    
# Script2-3
    public void SetPower(int value)
    {
        power+=value;
        print("power has been increased as " +value+ ", total power is "+power);
    }
    
# Script2-3
    public void SetDefence(int value)
    {
        defence+=value;
        print("defence has been increased as " +defence+ ", total power is "+defence);
    }

    void Start(){
        OnStart+=SetPower; //call event
        OnStart+=SetDefence;
    }

    private void OnDisable()
    {
        OnStart(5);
    }
}

 

Script2. (class 2)

1. Accesses the function from other class in other script.

2. Adds current class function to 1.

3. When it executes, it called all the functions at the same time.

# 1
public class part2 : MonoBehaviour
{
    void Start()
    {
# 2
        part.OnStart+=abc; //access the class from other script, and added 'abc'function from current script
    }
# 3    
    public void abc(int value)
    {
        print(value+" has been increased");
    }
}

>>>
5 has been increased
power has been increased as 5, total power is 5
defence has been increased as 5, total defence is 5