How to pass on information through C# events?

I’m rather new to programming and in particular to using C# (I have used Actionscript3 before now), and would like to know how to pass on data through events using C#'s event system.

For example, in ActionScript3, an event like a mousebutton click you could extract what object was clicked on from the data that is passed with the event.

From the tutorial available on the Unity website on how to use public delegates and events, I have only learned how to create and call blank events that do not pass any data.

I would be most thankful if someone could provide an example of how to pass on some data through an event call, or point me to an online resource explaining it.

How about: [http://www.youtube.com/watch?v=N2zdwKIsXJs][1] If you are already creating blank events, you are 90% of the way there. [1]: http://www.youtube.com/watch?v=N2zdwKIsXJs

1 Answer

1

This example shows how to use an event and passing a string through it.

using UnityEngine;

public class UnityAnswers : MonoBehaviour
{
    void Start ()
    {
        // Whenever Unity Answers, call QuestionAnswered.
        OnUnityAnswers += QuestionAnswered;

        // Answer the question.
        RaiseAnswer("Great, someone made you a script example.");
        RaiseAnswer("Now, read the comments and play around with it.");
    }

    // Note: None of the following has to be 'public', they could also be 
    // 'private', 'protected', 'internal' or 'protected internal'.
    // But, let's keep it simple.    

    // This functions signature matches the callback signature! (Important)
    // Has: Return of type 'void' and 1 parameter of type 'string'
    public void QuestionAnswered (string message)
    {
        // Some dummy example code.
        Debug.Log(message);
    }

    // Callback signature
    // Has: Return of type 'void' and 1 parameter of type 'string'
    public delegate void AnswerCallback (string message);

    // Event declaration
    public event AnswerCallback OnUnityAnswers;

    // Calls, "raises" or "invokes" the event. Note that if no one subscribed
    // to the event, the event will be null. We need to check this first to
    // prevent errors.
    public void RaiseAnswer (string message)
    {
        if (OnUnityAnswers != null)
            OnUnityAnswers(message);
    }
}

Thank you, very clear example :)