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 } 
1

1 Answer 1

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 }); 
Sign up to request clarification or add additional context in comments.

5 Comments

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 if it is throwing an exception, then you haven't subscribed to the event. So: subscribe to the event!
miene.ClickEvent += (s, args) => { //some useless stuff }; Isn't that a subscribe
@Manubown yes, but if the event is still null: you haven't done that - or maybe not on the right target object
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.