writing event_management in unity

32 views Asked by At

I am new to unity programming. I am reading the mastering unity scripting by alan thorn... now I am studying event driven programming. I am really confused about this code:

public delegate void OnEvent(EVENT_TYPE Event_Type, Component Sender, object Param = null);

What is the meaning of object param = null, what does that code mean?

Is there any videos or books which teaches event driven programming in unity step by step?

Is there any concept that I should learn? Can someone teach me the event driven programming step by step?

I searched a lot on web but there where no useful resources. Is there any simple article about writing an event management in unity?

1

There are 1 answers

2
HalliHax On

Default Parameters

object Param = null

This is just a default parameter - meaning if the caller does not pass in a value for the parameter named 'Param', then it will use the default value, which in this case is null. Default parameters have no particular relation to C# events and delegates, and you'll find them in many places throughout the Unity APIs.

Events and Delegates

Using events and delegates in Unity is no different to using them in any other C# program - so the easiest thing to do is to learn about them outside of Unity first, and then apply them once you have a better understanding.

Here's a simple Hello World example:

using System;
                
public class Program
{
    class EventExample{
        //Handlers for OnEvent must adhere to this specification - i.e. must accept a string
        public delegate void StringEvent(string message);

        //An event that can be fired.
        public event StringEvent OnEvent;
    
        //Trigger the event
        public void FireEvent(string message)
        {
            OnEvent.Invoke(message);    
        }
    }

    private static void EventListener(string message){
         Console.WriteLine($"Event was fired with message: {message}");
    }


    public static void Main()
    {
        EventExample ee = new EventExample();

        //Assign an event handler
        ee.OnEvent += EventListener;

        //Trigger the event
        ee.FireEvent("Hello world!");
    }
}