- Home /
The question is answered, right answer was accepted
Delegates throws error when no observers present
In my game, whenever a certain delegate is called a NullReferenceException is thrown if there are no observers yet instantiated. I realise a try-catch statement could fix this, but why would it get thrown? Could it just not use the method anywhere?
Hi again.
Have you got the code and stack trace please?
Also be-careful with the conflation of delegates and observers. There is overlap but they are not the same thing.
Answer by sacredgeometry · Aug 10, 2019 at 11:55 AM
You can null check it before calling it. If you want a clean syntax try the null propagation syntax.
https://davefancher.com/2014/08/14/c-6-0-null-propagation-operator/
There's not really a code sample - just a call of 'troopAddObservers(e as Troop)' that causes a NullReferenceException. Which code would you like? It works with a simple try-catch anyway.
Well that could be calling a null reference exception in a few places.
Do me a favour. $$anonymous$$ove the cast above the method call and debug its value:
var troop = e as Troop;
Debug.Log(troop);
If it's null, then thats your cause if not its probably as I said.
Try/ Catch/ Finally blocks are for exception handling not just for consu$$anonymous$$g exceptions. haha
It will stop it falling over but it doesn't fix the problem.
It's not null, it's as you said :). Thanks!
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to set different classes at runtime 2 Answers
How do Delegates and Events work? 1 Answer
How to unsubscribe from InputSystem event properly 0 Answers