Wondering About the usage of event.

Hello ,

This Is my script, I Declare a delegate, Adding “event” Key word when referencing the delegate won’t change or do anything… So why do we need “Events?”

You can see what I mean in the code, I explained with “//” what do I mean,
Thank you In advance.

public class anotherScript
{
    public delegate void TestDelegate(object sender, GameObject gameObject);
    public event TestDelegate testDelegate;
// public TestDelegate testDelegate; - can also remove the "event" keyword and it won't do any change.
 
    public override void Awake()
    {
        testDelegate += CallEvent;
        testDelegate += CallEvent2;
        foreach (GameObject gameobject in GameObjectManager.gameObjects)
        {
            testDelegate(this, gameobject);
        }
    }
    public void CallEvent(object sender, GameObject e)
    {
        Console.WriteLine(e.kills);
    }
    public void CallEvent2(object sender, GameObject e)
    {
        Console.WriteLine(e.flagCapture);
    }

}

There’s not much difference, they event keyword basically does two things:

  • Limit the access to the delegate. From outside the class it’s only possible to add/remove listeners, only code inside the class can raise or clear the event.
  • It turns the event into something like a property, where you can override the add/remove accessors, similar to a property’s get/set accessors.

In your test case, everything is in a single class, so you don’t see a difference. Try it with to separate classes and you’ll see the additional access limitations when adding the event keyword.