1

I get a NullRefernceException even though I subscribed to the event in an Start Methode.

Where I create my Event:

public EventHandler<CustomArgs> ClickEvent;

    private void OnMouseDown()
    {
        Debug.Log("Clicked");
        CustomArgs args = new CustomArgs();
        args.Name = gebäude.ToString();
        args.Level = Level;
        args.MenuePosition = Menue;

        ClickEvent?.Invoke(this, args);
    }

Where I subscribe to my Event:

private void Start()
    {
        miene.ClickEvent += ClickEvent;
        Debug.Log("Event Addedet");
    }

    private void ClickEvent(object sender, CustomArgs e)
    {
        //some useless stuff 
    }
Manubown
  • 21
  • 3
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Pavel Anikhouski May 03 '20 at 20:34

1 Answers1

1

Events are null when no-one has subscribed. Fortunately, modern C# makes this easy:

ClickEvent?.Invoke(this, args);

With older language versions, you need to be more verbose:

var handler = ClickEvent;
if (handler != null) handler(this, args);

They mean exactly the same thing.

As a small optimisation, you may wish to defer creating the CustomArgs object until you know someone cares, though:

ClickEvent?.Invoke(this, new CustomArgs {
    Name = gebäude.ToString(),
    Level = Level,
    MenuePosition = Menue
});
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Yes, this is fixing the error, but not the problem. I need this Invoke because I want to do something when I get the mouse down – Manubown May 03 '20 at 20:18
  • @Manubown if it is throwing an exception, then you **haven't subscribed to the event**. So: subscribe to the event! – Marc Gravell May 03 '20 at 20:37
  • miene.ClickEvent += (s, args) => { //some useless stuff }; Isn't that a subscribe – Manubown May 03 '20 at 22:27
  • @Manubown yes, but if the event is still null: **you haven't done that** - or maybe not on the right target object – Marc Gravell May 03 '20 at 22:30
  • i have writen the subscribe command in the Update method and the OnMouseDown is a button click so I thing the Update method will be done bevor the button click. – Manubown May 03 '20 at 22:34